转换varchar值时转换失败' Truck'到数据类型位

时间:2016-06-13 15:29:07

标签: sql sql-server

当我尝试运行以下查询时。它工作得很好。

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 个答案:

答案 0 :(得分: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)