我使用下面的T-SQL删除名称在tblCtrlTable
中的表:
Declare @Cmd nvarchar(max)
select @cmd = (
SELECT 'IF OBJECT_ID(''' +TABLE_NAME + ''') IS NOT NULL BEGIN DROP TABLE [' + TABLE_NAME + '] END;'
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME IN (SELECT [TEST_TABLE] from tblCtrlTable WHERE FieldX=1 and FieldY = 'Pass'))
print @cmd
--EXECUTE sp_executesql @cmd
但是,我不断收到错误消息:
子查询返回了多个值。当子查询遵循=,!=,<,<=,>,> =或将子查询用作表达式时,不允许这样做。
我要去哪里错了?
答案 0 :(得分:2)
这是您执行此操作的一种方法。它不能确保值的顺序,但是它非常快捷,容易。不太确定为什么要检查object_id是否有效....由于它是一个表,所以不能为NULL。而且您知道它是一个表,因为您正在查询INFORMATION_SCHEMA.TABLES。 :)
Declare @Cmd nvarchar(max) = '' --Notice this is initially set to an empty string.
select @cmd = @cmd + 'IF OBJECT_ID(''' +TABLE_NAME + ''') IS NOT NULL BEGIN DROP TABLE [' + TABLE_NAME + '] END;'
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME IN (SELECT [TEST_TABLE] from tblCtrlTable WHERE FieldX=1 and FieldY = 'Pass')
print @cmd
答案 1 :(得分:1)
尝试使用Table变量而不是变量:
Declare @Cmd TABLE (QUERY nvarchar(max))
INSERT INTO @Cmd(QUERY)
SELECT
'IF OBJECT_ID(''' + TABLE_NAME + ''') IS NOT NULL BEGIN DROP TABLE [' + TABLE_NAME + '] END;'
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME IN (SELECT
[TEST_TABLE]
FROM tblCtrlTable
WHERE FieldX = 1
AND FieldY = 'Pass')
SELECT * FROM @cmd