简体   繁体   中英

Parameterized dynamic sql returns no results

From a C# application I create the following parameterized dynamic sql statement as captured by SQL profiler:

Executing this statement returns no results:

exec sp_executesql N'SELECT IDWebFormAnswer FROM WebFormAnswers WHERE IDWebform = 55 AND IDWebFormQuestion = 478 AND (ANSWER = ''@answer0'')', N'@answer0 nvarchar(2)', @answer0=N'XL'

However, if I simply replace @answer0 with XL in the following, I get 4 rows returned.

exec sp_executesql N'SELECT IDWebFormAnswer FROM WebFormAnswers WHERE IDWebform = 55 AND IDWebFormQuestion = 478 AND (ANSWER = ''XL'')', N'@answer0 nvarchar(2)', @answer0=N'XL'

I do not understand why this happens? Am I building the query wrong?

When you use a parameter you should not enclose it in quotes. If you do that then the parameter name becomes a literal string. With your code the query search for an ANSWER that contains the value '@Answer0' and there is none.

 exec sp_executesql N'SELECT IDWebFormAnswer FROM WebFormAnswers 
      WHERE IDWebform = 55 AND IDWebFormQuestion = 478 AND 
      (ANSWER = @answer0)', N'@answer0 nvarchar(2)', @answer0=N'XL'

Steve already answered it well so I will try and give some tips that I picked up through my several failures while working with Dynamic SQL. Hope it is useful.

First write out your query as such with all parameter declaration

DECLARE @answer0 nvarchar(2)

SELECT IDWebFormAnswer
FROM WebFormAnswers
WHERE IDWebform = '55'
  AND IDWebFormQuestion = '478'
  AND (ANSWER = @answer0)

Now replace all single quotes with 2 Single quotes (I use CTRL+H, replace ' with '')

DECLARE @answer0 nvarchar(2)

SELECT IDWebFormAnswer
FROM WebFormAnswers
WHERE IDWebform = ''55''
  AND IDWebFormQuestion = ''478''
  AND (ANSWER = @answer0)

Next Break this query down and encapsulate with leading and trailing Single quotes and integrate with sp_executesql syntax.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM