开发者

writing an Dynamic query in sqlserver

开发者 https://www.devze.com 2022-12-25 05:36 出处:网络
DECLARE @sqlCommand varchar(1000) DECLARE @columnList varchar(75) DECLARE @city varchar(75) DECLARE @regio开发者_运维知识库n varchar(75)

DECLARE @sqlCommand varchar(1000) DECLARE @columnList varchar(75) DECLARE @city varchar(75) DECLARE @regio开发者_运维知识库n varchar(75) SET @columnList = 'first_name, last_name, city' SET @city = '''London''' SET @region = '''South''' SET @sqlCommand = 'SELECT ' + @columnList + ' FROM dbo.employee WHERE City = ' + @city and 'region = '+@region --and 'region = '+@region print(@sqlCommand) EXEC (@sqlCommand)

when i run this command i get an error

Msg 156, Level 15, State 1, Line 8 Incorrect syntax near the keyword 'and'.

and help would great thank you


'and' must come under single quote

@sqlCommand = 'SELECT ' + @columnList + ' FROM dbo.employee WHERE City = ' +  @city  + 'and region = '  + @region 


A must read for everybody who use dynamic SQL: http://www.sommarskog.se/dynamic_sql.html


I'd recommend using parameterised SQL to help guard against sql injection, and to support execution plan reuse. So assuming @columnList is fully validated and therefore guaranteed to not include anything dodgy:

DECLARE @sqlCommand nvarchar(1000)
DECLARE @columnList varchar(75)
DECLARE @city varchar(75)
DECLARE @region varchar(75)
SET @columnList = 'first_name, last_name, city'
SET @city = 'London'
SET @region = 'South'
SET @sqlCommand = 'SELECT ' + @columnList + ' FROM dbo.employee WHERE City = @city AND region = @region'
print(@sqlCommand)

EXEC sp_executesql @sqlCommand, N'@city varchar(75), @region varchar(75)', @city, @region

I'm assuming that your situation isn't exactly as outlined as it would be better to not use dynamic sql at all otherwise.


Try to replaced your SET @sqlCommand code with this:

SET @sqlCommand = 'SELECT ' + @columnList + ' FROM dbo.employee WHERE City = ' + @city  + ' and  region = '+@region 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号