Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic SQL gives "Incorrect Syntax Near '+'"

I am probably being extremely dumb here but why does this simple dynamic query:

EXEC sp_executesql N'SELECT Id FROM dbo.Widgets WHERE Id = ' + 1;

Give "Incorrect syntax near '+'"

?

like image 215
Kev Avatar asked Jul 12 '26 09:07

Kev


1 Answers

You can't formulate the expression as part of the argument. And you shouldn't be concatenating that way anyway (think SQL injection) - you're using sp_executesql already, why not use a proper parameter?

DECLARE @Id INT, @sql NVARCHAR(MAX);
SET @Id = 1; -- presumably this will come from elsewhere

SET @sql = N'SELECT Id FROM dbo.Widgets WHERE Id = @Id;';
EXEC sp_executesql @sql, N'@Id INT', @Id;
like image 128
Aaron Bertrand Avatar answered Jul 14 '26 02:07

Aaron Bertrand