我列出了需要从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脚本?
答案 0 :(得分:2)
DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = (
SELECT '
IF OBJECT_ID(''' + obj + ''', ''U'') IS NOT NULL BEGIN
DROP TABLE ' + obj + '
PRINT ''' + obj + ' has been dropped''
END
'
FROM (
SELECT obj = QUOTENAME(s.name) + '.' + QUOTENAME(o.name)
FROM sys.objects o
JOIN sys.schemas s ON o.[schema_id] = s.[schema_id]
WHERE o.[type] = 'U'
--AND o.name LIKE 'table%'
--AND s.name IN ('dbo')
) t
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')
PRINT @SQL
--EXEC sys.sp_executesql @SQL
输出 -
IF OBJECT_ID('[dbo].[user_data]', 'U') IS NOT NULL BEGIN
DROP TABLE [dbo].[user_data]
PRINT '[dbo].[user_data] has been dropped'
END
IF OBJECT_ID('[dbo].[formatter_options]', 'U') IS NOT NULL BEGIN
DROP TABLE [dbo].[formatter_options]
PRINT '[dbo].[formatter_options] has been dropped'
END
答案 1 :(得分: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;
如果您使用低于2012的SQL Server
版本,则需要使用字符串连接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
修改强>
工作原理:
GROUP_CONCAT
中的MySQL
类似。您可以将其视为将多个IF BEGIN END
块组合成一个字符串的方法。FORMATMESSAGE
会将%s
替换为实际的表名(引用以避免SQL注入攻击)PRINT
用于调试以检查生成的查询,可以注释sp_executesql
将执行SQL字符串