我正在尝试从每个服务器中删除表。我的服务器1有3个数据库,服务器2有6个,服务器3有8个。
下面是我编写的SQL脚本,用于从特定服务器中的每个数据库执行删除操作。我执行这些操作后。
DECLARE
@LoopId int,
@Command varchar(500),
@tblName varchar(100)
DECLARE @List TABLE
(
TableName sysname not null,
LoopId int not null identity(1,1)
)
-- Load with tables you wish to drop
INSERT @List (TableName)
SELECT name FROM [Morgage].sys.objects WHERE type = 'u' and name like '%JKL%'
SELECT name FROM [Scorecard].sys.objects WHERE type = 'u'and name like '%JKL%'
SELECT name FROM [Core].sys.objects WHERE type = 'u' and name like '%JKL%'
SET @LoopId = @@rowcount
-- Go through list and process each item
WHILE @LoopId > 0
BEGIN
SET @tblName = (SELECT TableName from @List where LoopId = @LoopId)
SET @Command = 'Drop table ' + @tblName
execute (@Command)
SET @LoopId = @LoopId - 1
END
上面的查询结果显示受影响的行但是当我去尝试测试时使用下面的查询。我确实看到了一切。我的查询实际上做了什么?我做得对吗?
SELECT name FROM [Scorecard].sys.objects WHERE type = 'u'and name like '%JKL%'
任何帮助将不胜感激。谢谢。
答案 0 :(得分:0)
默认情况下,查询可能不会提交。尝试明确指定
答案 1 :(得分:0)
试试这个版本的脚本: -
DECLARE
@LoopId int,
@Command varchar(500),
@tblName varchar(100),
@dbName sysname
DECLARE @List TABLE
(
DBName sysname not null,
TableName sysname not null,
LoopId int not null identity(1,1)
)
-- Load with tables you wish to drop
INSERT @List (DBName, TableName)
SELECT 'Morgage',name FROM [Morgage].sys.objects WHERE type = 'u' and name like '%JKL%'
UNION
SELECT 'Scorecard',name FROM [Scorecard].sys.objects WHERE type = 'u'and name like '%JKL%'
UNION
SELECT 'Core',name FROM [Core].sys.objects WHERE type = 'u' and name like '%JKL%'
SET @LoopId = @@rowcount
-- Go through list and process each item
WHILE @LoopId > 0
BEGIN
SELECT @tblName = TableName, @dbName=DBName from @List where LoopId = @LoopId
SET @Command = 'USE ' + @dbName + ';if not exists(select 1 from sys.foreign_keys where parent_object_id=object_id(''' + @tblName + ''',''U'')' + char(10) + 'Drop table ' + @tblName + ';'
execute (@Command)
SET @LoopId = @LoopId - 1
END