开发者

Remove a row in an arbitrary table using data from a select statement

I have a table called开发者_如何学编程 "changes" which contains a list of record numbers the user has modified on many other tables. I'd like to remove the record referenced by a row in changes (and the changes row itself) in one SQL query.

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

Unfortunately, I keep getting errors about how 'changeRecnum' and 'number' are invalid column names.


You need to use Dynamic SQL to use a variable as a table name. Best way I think would be to set your name and number as @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

You need to read this article about Dynamic SQL though. It's bascially required reading for these scenarios.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜