在SQL中执行动态选择的查询

时间:2014-04-02 06:05:02

标签: sql multi-tenant

我使用的是Multi tenant Shared schema database,所以我有很多架构,

  

必需:   我想删除一些架构;因为我必须删除该架构中的所有CONSTRAINT表以删除表。我得到了查询列表以删除模式的所有CONSTRAINT以及从下面的代码中删除表的查询

     

问题:   从下面的代码我得到了一个查询列表,现在我是复制查询并手动执行该查询列表,我可以自动执行此操作吗?

代码

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);

1 个答案:

答案 0 :(得分:0)

使用COALESCE函数,我们可以将多行转换为SQL Server中的单个字符串

以下代码工作正常,删除架构中的所有表

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