Detach & Attach Procedure


/*
-->Created By- Vimal Lohani on 30-APR-2015
-->For successful run, Your sql server service account should have permission to old location & new location
-->Exec uspDetachAttach @DbName=<Database Name>, @NewLocationPath=<new Location for database like 'D:\Data'>
*/
CREATE PROCEDURE uspDetachAttach @DbName VARCHAR(200)
 ,@NewLocationPath VARCHAR(2000)
AS
BEGIN
 SET NOCOUNT ON

 DECLARE @Sql VARCHAR(max)
 DECLARE @OldLocation VARCHAR(2000)
 DECLARE @Size FLOAT
 DECLARE @max INT

 --Getting Database & Drive information
 SELECT ROW_NUMBER() OVER (
   ORDER BY fs.database_id
   ) 'RowNo'
  ,fs.database_id
  ,fs.size * 8.0 / 1024 size
  ,fs.physical_name 'OldLocation'
  ,reverse(left(reverse(fs.physical_name), charindex('\', reverse(fs.physical_name)) - 1)) 'FileName'
 INTO #temp
 FROM sys.databases db
 INNER JOIN sys.master_files fs ON fs.database_id = db.database_id
 WHERE fs.database_id NOT IN (
   1
   ,2
   ,3
   ,4
   ) --Not considered system databases
  AND db.NAME = @DbName

 SELECT @max = max(RowNo)
 FROM #temp

 IF (
   (
    SELECT Count(*)
    FROM #temp
    ) = 0
   )
 BEGIN
  PRINT 'database not exist so return'

  RETURN
 END
 ELSE
 BEGIN
  SELECT @Size = Sum(Size)
  FROM #temp

  DECLARE @drive TABLE (
   drive VARCHAR(2)
   ,MBfree FLOAT
   )

  INSERT INTO @drive
  EXEC master..xp_fixeddrives

  --Select * from @drive
  IF (
    (
     SELECT MBfree
     FROM @drive
     WHERE drive = SUBSTRING(@NewLocationPath, 1, 1)
     ) < (
     SELECT @Size
     )
    )
  BEGIN
   PRINT 'Size not available so return'

   RETURN
  END
  ELSE
  BEGIN
   --Detach database files
   SET @Sql = 'USE MASTER;
           ALTER DATABASE ' + @DbName + '
           SET SINGLE_USER
           WITH ROLLBACK IMMEDIATE;
           EXEC MASTER.dbo.sp_detach_db @dbname = N''' + @DbName + '''
           '

   EXEC (@Sql)

   -- Move MDF File from Loc1 to Loc 2
   DECLARE @file VARCHAR(2000)

   EXEC master.dbo.sp_configure 'show advanced options'
    ,1

   RECONFIGURE

   EXEC master.dbo.sp_configure 'xp_cmdshell'
    ,1

   RECONFIGURE

   IF ((Substring(REVERSE(@NewLocationPath), 1, 1)) <> '\')
    SET @NewLocationPath = @NewLocationPath + '\'
   SET @NewLocationPath = @NewLocationPath + @DbName + '\'

   EXEC master.dbo.xp_create_subdir @NewLocationPath

   WHILE (@max > 0)
   BEGIN
    SELECT @file = 'move "' + Cast(OldLocation AS VARCHAR(1000))
    FROM #temp
    WHERE RowNo = @max

    SELECT @file = @file + '" "' + @NewLocationPath + (
      SELECT FileName
      FROM #temp
      WHERE RowNo = @max
      )

    SET @file = @file + '"'

    PRINT @file

    EXEC master.dbo.xp_cmdshell @file

    SET @file = ''
    SET @max = @max - 1
   END

   -- Re-Attached DB
   SELECT @file = IsNull(@file, '') + '( FILENAME = N''' + @NewLocationPath + '' + FileName + ''' ),'
   FROM #temp

   SELECT @file = 'CREATE DATABASE ' + @DbName + ' ON ' + SUBSTRING(@file, 1, LEN(@file) - 1) + 'FOR ATTACH'

   PRINT @file

   EXEC (@file)

   SET @file = 'ALTER DATABASE ' + @DbName + ' SET MULTI_USER;'

   EXEC (@file)

   EXEC master.dbo.sp_configure 'xp_cmdshell'
    ,0

   RECONFIGURE

   EXEC master.dbo.sp_configure 'show advanced options'
    ,0

   RECONFIGURE
  END
 END

 DROP TABLE #temp
END

Comma separated values from sql table :

--Create temp table & Insert data-----
Create table #temp(id int, tech nvarchar(10))
Insert into #temp(id,tech) values(12, 'c#'),(12,'java'),(13,'sql'),(13,'Oracle'),(13,'Mysql'),(15,'hadoop')
Select * from #temp
--------------------------------------
--Process data------------------------
;WITH cte AS
(
SELECT DISTINCT id 
FROM #temp
)
SELECT Id, STUFF((SELECT ', ' + CAST(t2.tech AS NVARCHAR(MAX))
     FROM #temp t2 WHERE t1.ID = t2.ID
     FOR XML PATH('')),1,1,'') skills
into #temp1
FROM cte t1
--Getting Result---------------------
Select * from #temp1
--Drop temp tables-------------------
Drop table #temp
Drop table #temp1
-------------------------------------



sp_MSforeachtable Stored Procedure

sp_MSforeachtable stored procedure provided by Microsoft, is used for smooth processing on all tables of a single database. So why to use complex query when we have already that procedure.

How and when to use sp_MSFooreachtable :

Parameters
sp_MSforeachtable @command1, @replacechar, @command2,  @command3, @whereand, @precommand, @postcommand

  • @command1 nvarchar(2000) – is the first command to be executed
  • @replacechar nchar(1) – is a character in the command string that will be replaced with the table name being processed (default character is “?”)
  • @command2 nvarchar(2000)-  additional command that can be run for each table. It runs after @ command1
  • @command2 nvarchar(2000)-  another additional command that can be run for each table. It runs after @ comman2
  • @whereand nvarchar(2000)- you can specify the where clause in this parameter
  • @precommand nvarchar(2000) -  specifies a command to be run prior to processing any table
  • @postcommand nvarchar(2000)- command to be executed  after all commands have been processed
Eg 1 : Retriving all tables starting with 'c' and their row count

CREATE TABLE  #rowcount (tablename varchar(128), cnt int)
EXEC sp_MSforeachtable
 @command1 = 'Insert into #rowcount select ''?'',
              count(*) from ?',
 @whereand = 'and o.name like ''p%''',
 @postcommand = 'SELECT * from #rowcount'

DROP TABLE  #rowcount

Eg 2:  Disabling all constraints on all tables
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
Eg 3:  Enabling all constraints on all tables

EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'
Eg 4:  Deleting rows from all tables

EXEC sp_MSForEachTable 'DELETE FROM ?'
Eg 5:  Reseed identity column

If any table doesn't contain identity column, it raise error and as a quality of stored procedure it will move on


EXEC sp_MSforeachtable 'DBCC CHECKIDENT ( ''?'', RESEED, 0)'


Eg 6:   Rebuild clustered index/all non clusted indexes on all the tables


EXEC sp_MSforeachtable 'ALTER INDEX ALL ON ? REBUILD WITH (ONLINE=OFF)'

Find only characters or only integer from alphanumeric value :

Find only characters from string :

DECLARE @Temp VARCHAR(100)='548STA123Ldfgh45df45df5446fg54645dfg546';
Declare @NumRange AS varchar(50) = '%[0-9]%';
    While PatIndex(@NumRange, @Temp) > 0
        SET @Temp = Stuff(@Temp, PatIndex(@NumRange, @Temp), 1 ,'')

 SELECT @Temp

====================================

Find only integers from string :

DECLARE @var VARCHAR(100)='5STA123Ldfgh45df45df5446fg54645dfg546';
DECLARE @intdata INT
SET @intdata = PATINDEX('%[^0-9]%', @var)
BEGIN
WHILE @intdata > 0
BEGIN
SET @var = STUFF(@var, @intdata, 1, '' )
SET @intdata = PATINDEX('%[^0-9]%', @var )
END
END

Select ISNULL(@var,0)

Find a float value from string :

DECLARE @var VARCHAR(100)='STA123.26dfg';
DECLARE @intdata INT
SET @intdata = PATINDEX('%[^0-9]%', @var)
BEGIN
WHILE @intdata > 0
BEGIN
SET @var = STUFF(@var, @intdata, 1, '' )
SET @intdata = PATINDEX('%[^0-9.]%', @var )
END
END

Select ISNULL(@var,0)

=====================================

Connection Property : Port, IP .....

To get locl tcp port and ip address:   

select distinct local_net_address, local_tcp_port from sys.dm_exec_connections where local_net_address     is not null

To get all information related to sql connections:   

 select * from sys.dm_exec_connections


=============================================

Query Connection Properties :

SELECT
   CONNECTIONPROPERTY('net_transport') AS net_transport,
   CONNECTIONPROPERTY('protocol_type') AS protocol_type,
   CONNECTIONPROPERTY('auth_scheme') AS auth_scheme,
   CONNECTIONPROPERTY('local_net_address') AS local_net_address,
   CONNECTIONPROPERTY('local_tcp_port') AS local_tcp_port,
   CONNECTIONPROPERTY('client_net_address') AS client_net_address

=============================================

When connecting locally,
Transport Protocol always comes “SHARED MEMORY” and TCP Port as NULL.

When connecting remotely,
Transport Protocol always comes “TCP” and TCP Port as negative number (if the port is set to dynamic port).


To get the actual port, just do a subtraction from a number “65536” and we get the actual port number.


Sql Installation

Code to check Sql Server Installation Date & Time :
SELECT @@SERVERNAME SERVERNAME, CREATE_DATE 'INSTALALTIONDATE'
FROM SYS.SERVER_PRINCIPALS
WHERE SID = 0X010100000000000512000000