2013-02-26 102 views
3

我試圖執行以下動態查詢,但我得到了一個錯誤:如果我將其更改爲普通查詢我無效的列名「貓」的SQL Server +動態查詢「無效的列名稱

DECLARE @SQLDelQuery AS NVARCHAR(1200) 
DECLARE @MemberNames varchar(50) 

SET @MemberNames = 'cat' 

     SET @SQLDelQuery = 'SELECT [Email] FROM [aspnet_Membership] am 
     INNER JOIN [aspnet_Users] u 
     ON (am.UserId = u.UserId) 
     INNER JOIN [Member] m 
     ON (am.UserId = m.UserId) 
     WHERE u.UserName IN (' + @MemberNames + ') 

    EXECUTE(@SQLDelQuery) 

我很好:

SELECT [Email] FROM [aspnet_Membership] am 
    INNER JOIN [aspnet_Users] u 
    ON (am.UserId = u.UserId) 
    INNER JOIN [Member] m 
    ON (am.UserId = m.UserId) 
    WHERE u.UserName IN ('cat') 

任何人都可以指出我的錯誤?謝謝。

回答

5

由於cat是你需要一個varchar包括它周圍的單引號,並且您需要將IN子句的右括號放在sql字符串的內部。

新的代碼將是:

DECLARE @SQLDelQuery AS NVARCHAR(1200) 
DECLARE @MemberNames varchar(50) 

SET @MemberNames = 'cat' 

     SET @SQLDelQuery = 'SELECT [Email] FROM [aspnet_Membership] am 
     INNER JOIN [aspnet_Users] u 
     ON (am.UserId = u.UserId) 
     INNER JOIN [Member] m 
     ON (am.UserId = m.UserId) 
     WHERE u.UserName IN (''' + @MemberNames + ''')' 

    EXECUTE(@SQLDelQuery) 

查看一個SQL Fiddle Demo印查詢字符串。這將生成一個查詢字符串是這樣的:

SELECT [Email] 
FROM [aspnet_Membership] am 
INNER JOIN [aspnet_Users] u 
    ON (am.UserId = u.UserId) 
INNER JOIN [Member] m 
    ON (am.UserId = m.UserId) 
WHERE u.UserName IN ('cat') -- cat surrounded in single quotes 
+0

謝謝bluefeet。有效。我不能投票因爲我需要50分 – 2017-05-10 08:56:50

1

您的字符串:

WHERE u.UserName IN (' + @MemberNames + ') 

將評估爲:

WHERE u.UserName IN (cat) 

因爲撇號你只是封裝字符串,並有字符串文字周圍沒有多餘的撇號。

您需要:

WHERE u.UserName IN (''' + @MemberNames + ''') 

或者,您可以按原樣留下您的查詢,並單獨撇號每個ID在你@MemberNames變量:

SET @MemberName = '''cat'''   -- for a single user 
SET @MemberName = '''cat'', ''dog''' -- for multiple users 
2

你需要把它作爲一個字符串傳遞到動態查詢

SET @MemberNames = '''cat''' 

差異在resulted query

WHERE u.UserName IN (cat) -- cat is taking as a column name here 
WHERE u.UserName IN ('cat') -- cat is taking as a string here 
0

您的動態查詢使用'字符作爲字符串分隔符,因此在構建字符串後,最後一行最終會像這樣讀取:

WHERE u.UserName IN (cat) 

據此,cat的讀取類似於列名。

要解決它,你需要在

`SET @MemberNames = '''cat'''` 

或字符串,要麼是定義,包括轉義字符'被用來構建SQL:

`WHERE u.UserName IN (''' + @MemberNames + ''')'`