使用select语句中的数据删除任意表中的行

时间:2010-10-06 15:52:52

标签: sql sql-server-2008

我有一个名为“changes”的表,其中包含用户在许多其他表上修改过的记录号列表。我想在一个SQL查询中删除更改中的行引用的记录(以及更改行本身)。

WITH name AS ( SELECT tableName FROM [changes] WHERE id = 80 ),
   number AS ( SELECT  changeRecnum FROM [changes] WHERE id = 80 )

DELETE FROM [name] WHERE changeRecnum = number

DELETE FROM [changes] WHERE id = 80

不幸的是,我一直在收到有关'changeRecnum'和'number'是无效列名的错误。

1 个答案:

答案 0 :(得分:0)

您需要使用动态SQL将变量用作表名。我认为最好的方法是将你的姓名和号码设置为@variables。

DECLARE @name varchar(100)
DECLARE @number int
DECLARE @SQL varchar(max)

SET @name = (SELECT tableName FROM [changes] WHERE id = 80)
SET @number = ( SELECT  changeRecnum FROM [changes] WHERE id = 80 )

SET @SQL = 'DELETE FROM [' + @name + '] WHERE changerecnum = ' + CAST(@number as varchar)
PRINT (@SQL)
EXEC (@SQL)

DELETE FROM [changes] WHERE id = 80

你需要阅读this article about Dynamic SQL。这些场景的基本要求是阅读。