2010-10-06 42 views
0

我有一個名爲「changes」的表,其中包含用戶在許多其他表上修改過的記錄號的列表。我想在一個SQL查詢中刪除一行中引用的記錄(以及更改行本身)的記錄。使用select語句中的數據刪除任意表中的一行

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'是如何失效的列名的錯誤。

+0

顯然[我的記憶很糟糕](http://stackoverflow.com/questions/3320320/pdo-and-microsoft-sql-must-declare-the-table-variable-p1)。 您不能使用參數作爲表名稱。 WITH計數作爲參數嗎? – James 2010-10-06 16:04:40

回答

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。對於這些場景來說,這是基本需要閱讀的。

相關問題