2016-06-13 64 views
-1

當我試圖運行下面的查詢時。它工作得很好。將varchar值'Truck'轉換爲數據類型位時轉換失敗

SELECT DelayId, DelayCategory, DelayReason FROM 
[TAMS].[DelayMaintenance] 
WHERE IsUtilized = 1 
AND Truck = 1 
union  SELECT 0, NULL, '--- Pick One----' 
ORDER BY DelayId 

enter image description here

但是,當我試圖使用在相同的查詢,但參數。它給了我一個錯誤。

Msg 245, Level 16, State 1, Line 4 
Conversion failed when converting the varchar value 'Truck' to data type bit. 

DECLARE @CheckPointType VARCHAR(50) = 'Truck' 
DECLARE @BitConveyance BIT = 1 

SELECT DelayId, DelayCategory, DelayReason FROM 
[TAMS].[DelayMaintenance] 
WHERE IsUtilized = 1 
AND @CheckPointType = @BitConveyance -- Issue is here 
union  SELECT 0, NULL, '--- Pick One----' 
ORDER BY DelayId 
+1

當然,你是這樣做的:'@CheckPointType = @ BitConveyance',但這些變量有不同的數據類型。似乎你想使用動態SQL,但你需要實際上做它的「動態」部分 – Lamak

+0

@Lamak。請建議我如何重寫這個來得到我的結果 – user1030181

+1

你不能使用一個變量作爲列名。 –

回答

1

正如@Lamak暗示的那樣,您需要使用動態SQL。像這樣的東西可能會工作

DECLARE @CheckPointType VARCHAR(50) = 'Truck' 
DECLARE @BitConveyance BIT = 1 
DECLARE @SQL NVARCHAR(MAX) 

SET @SQL = 'SELECT DelayId, DelayCategory, DelayReason FROM [TAMS].[DelayMaintenance] WHERE IsUtilized = 1 AND ' + @CheckPointType + ' = ' + CAST(@BitConveyance AS CHAR(1)) + 
      ' union  SELECT 0, NULL, ''--- Pick One----'' ORDER BY DelayId' 

EXEC (@SQL) 
相關問題