0

我正在尝试从每台服务器中删除表。我的服务器 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%'

任何帮助将不胜感激。谢谢。

4

2 回答 2

0

可能是查询默认不提交。尝试明确指定它

于 2013-03-11T00:04:01.667 回答
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
于 2013-03-11T00:17:05.713 回答