Question

I am using a Multi tenant Shared schema database, so i have so many schema,

Required: I want to remove some schema; for that i have to remove all the CONSTRAINT of tables in that schema to delete a table. I got the the list of query to remove all the CONSTRAINT of a schema and the query to delete the tables from below code

Question: From the below code i got a list of Queries,now i am copy that queries and executing that list of queries manually,can i do that automatically ?

Code

SET NOCOUNT ON;
DECLARE @SchemaName nvarchar(250)
SET @SchemaName='schemaname1'

--Step 1: Remove all CONSTRAINT

SELECT 'ALTER TABLE ' +'[' + s.name + '].[' + t.name + ']' +' DROP CONSTRAINT [' + f.name +']'
FROM sys.foreign_keys f
INNER JOIN sys.TABLES t ON f.parent_object_id=t.object_id
INNER JOIN sys.schemas s ON t.schema_id=s.schema_id
WHERE t.is_ms_shipped=0
and t.schema_id = schema_id(@SchemaName);

--Step 2: Drop all Tables
SELECT 'DROP TABLE ' + '[' + s.name + '].[' + t.name + ']'
FROM sys.TABLES t
INNER JOIN sys.schemas s ON t.schema_id=s.schema_id
WHERE t.is_ms_shipped=0 and t.schema_id = schema_id(@SchemaName);
Was it helpful?

Solution

Using COALESCE function we can turn multiple rows into a single string in SQL Server

Following code is working fine, to delete All the table in a Schema

SELECT * INTO #mytemp FROM INFORMATION_SCHEMA.SCHEMATA 
WHERE  [SCHEMA_NAME] in ('schemaname1','schemaname2','schemaname3')

WHILE  (SELECT Count(*) FROM #mytemp) > 0
BEGIN
    DECLARE @SCHEMA_NAME varchar(100)
    SELECT @SCHEMA_NAME = [SCHEMA_NAME] FROM #mytemp
    DECLARE @SQL VARCHAR(MAX)
    SET  @SQL='';

    --Step 1: Remove all CONSTRAINT
    SELECT @SQL= COALESCE(@SQL,'') +'ALTER TABLE ' +'[' + s.name + '].[' + t.name + ']' +' DROP CONSTRAINT [' + f.name +']'+ ' ; '  
    FROM sys.foreign_keys f
    INNER JOIN sys.TABLES t ON f.parent_object_id=t.object_id
    INNER JOIN sys.schemas s ON t.schema_id=s.schema_id
    WHERE t.is_ms_shipped=0
    and t.schema_id = schema_id(@SCHEMA_NAME);

    --Step 2: Drop all Tables
    SELECT @SQL= COALESCE(@SQL,'')+'DROP TABLE ' + '[' + s.name + '].[' + t.name + ']'+ ' ; ' 
    FROM sys.TABLES t
    INNER JOIN sys.schemas s ON t.schema_id=s.schema_id
    WHERE t.is_ms_shipped=0 and t.schema_id = schema_id(@SCHEMA_NAME);

    EXEC(@SQL)
    --Custom Query End
    DELETE #mytemp WHERE [SCHEMA_NAME] = @SCHEMA_NAME

END
DROP TABLE #mytemp
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top