2016-03-07 43 views
-2
declare 
@columnName varchar(30) 
set @columnName = 'February' 

declare 
@year int 
set @year = 2016 

Declare @abc varchar(max) 
set @abc = 'Update XYZ'+' '+ @columnName+ '=  562 WHERE Year =' +' '+ convert(varchar(6),@year)+' ' 
+ 'AND Category = RESOLUTION'+' ' +'AND Support_KPI = P1_Gold' 
print @abc 

execute (@abc) 

上執行這個代碼,我得到這個作爲結果的列:無法更新存儲在一個變量

Update XYZ SET February= 562 
WHERE Year = 2016 AND Category = RESOLUTION AND Support_KPI = P1_Gold 

消息207,級別16,狀態1,行1 無效專欄名稱'RESOLUTION'。 消息207,級別16,狀態1,行1 無效的列名稱'P1_Gold'

有什麼辦法擺脫這個錯誤,並獲得正確的列名?

+2

首先,發生什麼錯誤?其次,你爲什麼期待這個工作?你說該列可以包含「January」到「December」,那麼你爲什麼試圖在其中存儲值「876」? – reduckted

+0

@SaurabhMishra:你錯過了單引號。 – Wanderer

回答

0

創建動態SQL查詢和使用EXEC | EXECUTIVE

查詢

Declare @sql as varchar(max); 
Declare @ColumnName varchar(20); 
set @ColumnName = 'January'; -- Change this according to your requirement 
select @sql = 'update XYZ set ' + @ColumnName + ' = 876 where Year = 2016;'; 
execute(@sql); 

編輯

如果varcharwhere條件類型列,那麼我們就應該逃避單引號執行它通過加倍他們:

查詢

Declare @sql as varchar(max); 
Declare @ColumnName varchar(20); 
set @ColumnName = 'January'; -- Change this according to your requirement 
select @sql = 'update XYZ set ' + @ColumnName + 
       ' = 876 where Year= 2016 and Category = ''Resolution'' and Ticket = ''Met'';'; 
execute(@sql); 
+0

如果還有其他欄位在哪裏,那麼如何實現呢?像 更新XYZ設置@columnName = 876其中Year = 2016和Category ='Resolution'和Ticket ='Met' 我無法將其他列的值寫入引號(因爲它們是varchar)。任何可能的解決方案? –

+0

你必須逃脫單引號 – Wanderer

+0

感謝@Ullas ..我明白了:) –

0

在您的查詢 '決議' 和 'P1_Gold' 不是列,但這些都值。在SQL中,varchar值應該用單引號進行修飾。 所以你的查詢應該是這樣的:

DECLARE @Query AS VARCHAR(MAX) 
DECLARE @year INT 
SET @Year = 2016 
DECLARE @ColumnName VARCHAR(30) 

SET @ColumnName = 'February' 
SELECT @Query = 'UPDATE XYZ SET ' + 
@ColumnName + ' = 562 WHERE Year= '+ CONVERT(VARCHAR(6),@Year) + 
' AND Category = ''Resolution'' and Support_KPI = ''P1_Gold''' 
EXECUTE(@Query)