2010-03-30 64 views
1

DECLARE @sqlCommand VARCHAR(1000) DECLARE @columnList VARCHAR(75) DECLARE @city VARCHAR(75) DECLARE @region VARCHAR(75) SET @columnList =「名字,姓氏的動態查詢,城市' SET @city ='''London''' SET @region ='''South''' SET @sqlCommand ='SELECT'+ @columnList +'FROM dbo.employee WHERE City ='+ @city和 '區=' + @區域 --and '區=' + @區域 打印(@sqlCommand) EXEC(@sqlCommand)寫入SQLSERVER

當我運行此命令我得到一個錯誤

Msg 156,Level 15,State 1,Line 8 關鍵字'和'附近的語法不正確。

和幫助會很大謝謝

回答

2

'和' 一定要來下單引號

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

嘗試替換爲您的SET @sqlCommand代碼:

SET @sqlCommand = 'SELECT ' + @columnList + ' FROM dbo.employee WHERE City = ' + @city + ' and region = '[email protected] 
1

我建議使用參數化SQL來幫助防範sql注入,並支持執行計劃重用。因此,假設@columnList被充分驗證,因此保證不包含任何狡猾:

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 

我假設你的情況是不完全的概括因爲這將是最好不要使用動態SQL在所有其他。