How to Truncate only the Selected Tables from Database

How to Truncate only the Selected Tables from Database

How to Truncate only the Selected Tables from Database? This stored procedure helps you out in truncating the selected tables. These tables has to be passed as a string parameter to the stored procedure.  

 
 
We came up with a stored procedure. Here we go.
 
--EXEC USP_Truncate_Tabs '''MEMBER_DIM'',''CLAIM_FACT'',''CLAIM_TYPE_DIM'',''POS_TYPE_DIM'''

CREATE PROC USP_Truncate_Tabs(@String VARCHAR(7500))
AS
BEGIN
SET NOCOUNT ON
DECLARE @Constraints TABLE(ID INT IDENTITY,DropStmt VARCHAR(1000),CreateStmt VARCHAR(1000))
DECLARE @Tab TABLE(ID INT IDENTITY,TabName VARCHAR(200))
DECLARE @SQL1 VARCHAR(8000)
SET @SQL1='SELECT NAME FROM sysobjects  WHERE TYPE=''U'' AND name in('+(@String)+')'

/** Getting only selected tables details into @Tab **/
INSERT INTO @Tab EXEC(@SQL1)

/** Insert all Create and Drop Constraint Statements into a Temp Table *******/
 
INSERT INTO @Constraints (DropStmt,CreateStmt)
SELECT
  'ALTER TABLE ['+ ForeignKeys.ForeignTableSchema +
      '].['+ ForeignKeys.ForeignTableName +
      '] DROP CONSTRAINT [' + ForeignKeys.ForeignKeyName + ']; '
,'ALTER TABLE ['+ ForeignKeys.ForeignTableSchema +
      '].['+ ForeignKeys.ForeignTableName +
      '] WITH CHECK ADD CONSTRAINT ['+  ForeignKeys.ForeignKeyName +
      '] FOREIGN KEY(['+ ForeignKeys.ForeignTableColumn +
      ']) REFERENCES [' + schema_name(sys.objects.schema_id) + '].[' +
  sys.objects.[name] + ']([' +
  sys.columns.[name] + ']);  '
 from sys.objects
  inner join sys.columns
    on (sys.columns.[object_id] = sys.objects.[object_id])
  inner join (
    select sys.foreign_keys.[name] as ForeignKeyName
     ,schema_name(sys.objects.schema_id) as ForeignTableSchema
     ,sys.objects.[name] as ForeignTableName
     ,sys.columns.[name]  as ForeignTableColumn
     ,sys.foreign_keys.referenced_object_id as referenced_object_id
     ,sys.foreign_key_columns.referenced_column_id as referenced_column_id
     from sys.foreign_keys
      inner join sys.foreign_key_columns
        on (sys.foreign_key_columns.constraint_object_id
          = sys.foreign_keys.[object_id])
      inner join sys.objects
        on (sys.objects.[object_id]
          = sys.foreign_keys.parent_object_id)
        inner join sys.columns
          on (sys.columns.[object_id]
            = sys.objects.[object_id])
           and (sys.columns.column_id
            = sys.foreign_key_columns.parent_column_id)
    ) ForeignKeys
    on (ForeignKeys.referenced_object_id = sys.objects.[object_id])
     and (ForeignKeys.referenced_column_id = sys.columns.column_id)
 where (sys.objects.[type] = 'U')
  and (sys.objects.[name] not in ('sysdiagrams'))

/*** Drop all constraints in Database ****/
 
DECLARE @Sql VARCHAR(1000)
DECLARE @i INT,@Max INT
SELECT @Max=COUNT(1)FROM @Constraints
SET @i=1
WHILE(@i<=@Max)
BEGIN
SELECT @Sql=DropStmt FROM @Constraints WHERE ID=@i
EXEC(@Sql)
IF(@@ERROR<>0)
BEGIN
PRINT'Failed to Drop the Constraint : '+@Sql
END
SET @Sql=''
SET @i=@i+1
END
PRINT'All foreign keys are dropped successfully'

 
/*** Truncate selected Tables ****/
 

DECLARE @TabName VARCHAR(200)
SELECT @Max=COUNT(1)FROM @Tab
SET @i=1
WHILE(@i<=@Max)
BEGIN
SELECT @TabName=TabName FROM @Tab WHERE ID=@i
SELECT @Sql='TRUNCATE TABLE '+@TabName
EXEC(@Sql)
IF(@@ERROR<>0)
BEGIN
PRINT'Failed to Run the statement : '+@Sql
END
PRINT'Table '+@TabName+' Truncated'
SET @Sql=''
SET @i=@i+1
END

PRINT'All tables are truncated successfully'

/*** Recreate all constraints in Database ****/
 


SELECT @Max=COUNT(1)FROM @Constraints
SET @i=1
WHILE(@i<=@Max)
BEGIN
SELECT @Sql=CreateStmt FROM @Constraints WHERE ID=@i
EXEC(@Sql)
IF(@@ERROR<>0)
BEGIN
PRINT'Failed to Recreate the Constraint : '+@Sql
END
SET @Sql=''
SET @i=@i+1
END
PRINT'All foreign keys are recreated successfully'

END

/*** Execute SP to truncate the tables Emp, Dept, Emp_Add ***/
 
 
EXEC USP_Truncate_Tabs '''Dept'',''Emp'',''Emp_Add'''
 

 
 Output is like below

 

Posted in SQL Scripts | Tagged , , , , | Leave a comment

How to rebuild Master Database in SQL Server

How to rebuild Master Database in SQL Server

We recently resolved a request from a client that he is not able to access a SQL machine. We have logged into the sql box and we cam to know that the master database has been corrupted. IT is a SQL Server 2008 machine.

We generally use the statement shown below, using the “REBUILDDATABASE” option in setup.exe and the “/qn” parameter for installation to run silently:

Here is the script help us to know how to rebuild a master dtaabase in sql server

start /wait  setup.exe / qn
INSTANCENAME=  
REINSTALL=SQL_Engine
REBUILDDATABASE=1 
SAPWD=

 

We wondered , we found that the statement doe’s not work and still the problem alive. We almost had a 108 rounds around the Google and finally found the solution from a blog. It was really helped us in resolving the issue. We ran the below statement

setup.exe
/QUIET
/ACTION=REBUILDDATABASE 
/INSTANCENAME=instance_name 
/SQLSYSADMINACCOUNTS= accounts 
[/SAPWD=password] 
[/SQLCOLLATION=collation_name]

Thank God the database backed up and services were started , we have restored the master database with the latest backup and all the databases were online w/o any issue

 

Posted in SQL Scripts, SQL Server DBA | Tagged , , , , , , | Leave a comment

List of Replicated Tables

List Of Replicated Tables

 

This post helps you in getting the List of Replicated Tables. Recently some one from Dev team raised a request that he found mismatch for a Table on all replicated servers. At the routing server the table contains 6 rows and at some of the partition (Subscribers) the table contains 3 rows and remaining are at the proper sync levels. Now we need to check whether the table is subscribed to those where data is missing.

 To check that we could finally came with a Query which can save a lot of time. Lets assume the table name is “Test_Table” the connect to the publisher database and run the below query it’ll give us the total subscribers details to which the Table is subscribed

SELECT
pub.name AS [Publication],
art.name as [Article],
ser.name as [Subsriber],
sub.dest_db as [DestinationDB]
FROM
dbo.syssubscriptions sub
INNERJOINsys.servers ser ON ser.server_id = sub.srvid
INNERJOIN dbo.sysarticles art ON art.artid = sub.artid
INNERJOIN dbo.syspublications pub ON pub.pubid = art.pubid
WHERE art.Name='Test_Table'

The above query get you the list of replicated tables.

Posted in Uncategorized | Tagged , , , | Leave a comment