如何将表截断查询作为动态SQL

时间:2016-09-19 06:16:25

标签: sql-server dynamic-sql

我想将以下查询作为动态SQL。

查询1:表格截断

select 'Truncate Table '+''+ name from sys.tables where name like '%RND%'

查询2:

select 'Insert into  '+''+ name +'Select * from '+'.'+''+ name from sys.tables where name like '%RND%'

2 个答案:

答案 0 :(得分:0)

通过使用以下动态查询,您可以截断所需的表:

DECLARE @DynamicSQL AS VARCHAR(MAX) = '';

SELECT @DynamicSQL = @DynamicSQL + 'TRUNCATE TABLE ' + QUOTENAME(NAME) + '; '
FROM sys.tables
WHERE NAME LIKE '%RND%';

--PRINT @DynamicSQL
EXEC (@DynamicSQL)

对于第二个查询,动态查询为:

DECLARE @DynamicSQL1 AS VARCHAR(MAX) = '';

SELECT @DynamicSQL1 = @DynamicSQL1 + 'INSERT INTO ' + QUOTENAME(NAME) + ' SELECT * FROM ' + QUOTENAME(NAME) + '; '
FROM sys.tables
WHERE NAME LIKE '%RND%';

--PRINT @DynamicSQL1
EXEC (@DynamicSQL1)

答案 1 :(得分:0)

这可能就是你要找的东西

所有语句都收集在一个表中,按其插入点排序(idIDENTITY)。这肯定是 - 你以同样的方式建立第二个陈述没问题......

DECLARE @cmdTbl TABLE(id INT IDENTITY,cmd NVARCHAR(MAX));

INSERT INTO @cmdTbl(cmd) 
SELECT 'TRUNCATE TABLE ' + QUOTENAME(t.TABLE_CATALOG) + '.' + QUOTENAME(t.TABLE_SCHEMA) + '.' + QUOTENAME(t.TABLE_NAME) + ';'
FROM INFORMATION_SCHEMA.TABLES  AS t
WHERE t.TABLE_NAME LIKE '%RND%'

- 在收集所有语句后,我使用CURSOR一个接一个地执行它们。

DECLARE @cmd VARCHAR(MAX);
DECLARE cur CURSOR FOR SELECT cmd FROM @cmdTbl ORDER BY id;
OPEN cur;

FETCH NEXT FROM cur INTO @cmd;
WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT @cmd;
    --EXEC(@cmd); --For syntax check you start without EXEC...
    FETCH NEXT FROM cur INTO @cmd;
END
CLOSE cur;
DEALLOCATE cur;