在C#应用程序中,我创建了以下由SQL profiler捕获的参数化动态sql语句:
执行此语句不会返回任何结果:
exec sp_executesql N'SELECT IDWebFormAnswer FROM WebFormAnswers WHERE IDWebform = 55 AND IDWebFormQuestion = 478 AND (ANSWER = ''@answer0'')', N'@answer0 nvarchar(2)', @answer0=N'XL'
但是,如果我只是在下面用XL替换@ answer0,我会返回4行。
exec sp_executesql N'SELECT IDWebFormAnswer FROM WebFormAnswers WHERE IDWebform = 55 AND IDWebFormQuestion = 478 AND (ANSWER = ''XL'')', N'@answer0 nvarchar(2)', @answer0=N'XL'
我不明白为什么会这样?我是否构建了错误的查询?
答案 0 :(得分:5)
使用参数时,不应将其括在引号中。如果这样做,那么参数名称将成为文字字符串。使用您的代码,查询将搜索包含值“@ Answer0”的ANSWER,但没有。
exec sp_executesql N'SELECT IDWebFormAnswer FROM WebFormAnswers
WHERE IDWebform = 55 AND IDWebFormQuestion = 478 AND
(ANSWER = @answer0)', N'@answer0 nvarchar(2)', @answer0=N'XL'
答案 1 :(得分:0)
首先用所有参数声明
写出你的查询DECLARE @answer0 nvarchar(2)
SELECT IDWebFormAnswer
FROM WebFormAnswers
WHERE IDWebform = '55'
AND IDWebFormQuestion = '478'
AND (ANSWER = @answer0)
现在用2个单引号替换所有单引号(我使用CTRL + H,将'替换为'')
DECLARE @answer0 nvarchar(2)
SELECT IDWebFormAnswer
FROM WebFormAnswers
WHERE IDWebform = ''55''
AND IDWebFormQuestion = ''478''
AND (ANSWER = @answer0)
Next断开此查询,并使用前导和尾随单引号进行封装,并与sp_executesql语法集成。
DECLARE @SQLString nvarchar(500),
@ParmDefinition nvarchar(500),
@ParmValue1 nvarchar(2);
/* Build the SQL string one time.*/
SET @SQLString = N'SELECT IDWebFormAnswer
FROM WebFormAnswers
WHERE IDWebform = ''55''
AND IDWebFormQuestion = ''478''
AND (ANSWER = @answer0)';
SET @ParmDefinition = N'@answer0 nvarchar(2)';
/* Execute the string with the first parameter value. */
SET @ParmValue1 = N'XL';
EXECUTE sp_executesql @SQLString, @ParmDefinition,
@answer0 = @ParmValue1