小编典典

动态SQL脚本以生成删除表语句列表

sql

我列出了需要从SQL Server中删除的表(大约100 ++)。以下是我将使用的示例代码

IF OBJECT_ID('dbo.DS_Area_TBL', 'U') IS NOT NULL
drop table dbo.DS_Area_TBL
Print 'dbo.DS_Area_TBL has been dropped'

我需要将表名100 ++时间替换为其他表名。如何编写可以自动生成查询列表的动态sql脚本?


阅读 185

收藏
2021-04-28

共1个答案

小编典典

您可以先生成脚本,然后使用动态sql执行:

CREATE TABLE a(a INT);
CREATE TABLE b(a INT);
CREATE TABLE c(a INT);
CREATE TABLE d(a INT);
CREATE TABLE e(a INT);

CREATE TABLE tab(tab_name SYSNAME);   -- here are table names stored
INSERT INTO tab VALUES ('a'),('b'),('c'),('d'),('e');


-- main part
DECLARE @sql NVARCHAR(MAX);

SELECT @sql = STUFF((SELECT ' ' +  FORMATMESSAGE(
'IF OBJECT_ID(''%s'', ''U'') IS NOT NULL 
BEGIN
   DROP TABLE %s;
   PRINT ''%s has been dropped '';
END
', QUOTENAME(tab_name),QUOTENAME(tab_name),QUOTENAME(tab_name))
                   FROM tab
                   FOR XML PATH('')), 1, 1, '');

PRINT @sql;   -- for debug

EXEC [dbo].[sp_executesql]
    @sql;

如果您使用的版本SQL Server低于2012,则需要FORMATMESSAGE使用字符串串联进行更改+

您可以通过修改模板轻松地使用自定义架构扩展此脚本:

'IF OBJECT_ID(''%s'', ''U'') IS NOT NULL 
    BEGIN
       DROP TABLE %s;
       PRINT ''%s has been dropped '';
    END
'

输出:

IF OBJECT_ID('[a]', 'U') IS NOT NULL 
BEGIN
   DROP TABLE [a];
   PRINT '[a] has been dropped ';
END
 IF OBJECT_ID('[b]', 'U') IS NOT NULL 
BEGIN
   DROP TABLE [b];
   PRINT '[b] has been dropped ';
END
 IF OBJECT_ID('[c]', 'U') IS NOT NULL 
BEGIN
   DROP TABLE [c];
   PRINT '[c] has been dropped ';
END
 IF OBJECT_ID('[d]', 'U') IS NOT NULL 
BEGIN
   DROP TABLE [d];
   PRINT '[d] has been dropped ';
END
 IF OBJECT_ID('[e]', 'U') IS NOT NULL 
BEGIN
   DROP TABLE [e];
   PRINT '[e] has been dropped ';
END
2021-04-28