SQL server + dynamic query +'数据类型nvarchar和bit在add运算符中不兼容。

时间:2021-10-22 17:43:38

I am trying to join a string of database values but in this statement:

我试图加入一串数据库值,但在此声明中:

SET @sql = ('select' + @var1 + '+' + convert(varchar,@var2) + 
            'from [VoucherType] where [DeletedBy] is null and [AutoID] = 1')

I get an error saying

我说错了

The data types nvarchar and bit are incompatible in the add operator.

数据类型nvarchar和bit在add运算符中不兼容。

@var2 which is [IsBirthdayVoucher] in my database is a bit type but I have already applied convert(varchar, @var2) on it. Please kindly advice what I am doing wrong. Thanks.

@ var2是我的数据库中的[IsBirthdayVoucher]有点类型,但我已经应用了convert(varchar,@ var2)。请善意地告诉我做错了什么。谢谢。

SPROC:

declare @Str as varchar(max) 
declare @var1 as varchar(30)=null
declare @var2 as varchar(30)=null
declare @var3 as varchar(30)=null
declare @var4 as varchar(30)=null
declare @var5 as varchar(30)=null

declare @sql as varchar(355)

set @Str = '[Code][IsBirthdayVoucher][IsReusable]VouT' 

    Set @var1=  (select LEFT(@Str, CHARINDEX(']', @Str)))  
        set @Str = SUBSTRING(@Str, CHARINDEX(']', @Str) + 1, LEN(@Str))     
    Set @var2 =(select LEFT(@Str, CHARINDEX(']', @Str)))
        set @Str = SUBSTRING(@Str, CHARINDEX(']', @Str) + 1, LEN(@Str))         
    Set @var3 =(select LEFT(@Str, CHARINDEX(']', @Str)))  
        set @Str = SUBSTRING(@Str, CHARINDEX(']', @Str) + 1, LEN(@Str))     

    SET @sql = ('select' + @var1 + '+' + convert(varchar,@var2) + 'from [VoucherType] where [DeletedBy] is null and [AutoID] = 1')

          EXEC(@sql)

2 个解决方案

#1


4  

You're not converting [IsBirthdayVoucher] to VARCHAR, you're converting @var2 to VARCHAR.

您没有将[IsBirthdayVoucher]转换为VARCHAR,而是将@ var2转换为VARCHAR。

Try:

SET @sql = ('select ' + @var1 + ' + convert(varchar, ' + @var2 + ') from [VoucherType] where [DeletedBy] is null and [AutoID] = 1')

#2


0  

try this:

SET @sql = ('select CONCAT(' + @var1 + ',' + @var2 + ') from [VoucherType] where [DeletedBy] is null and [AutoID] = 1')

#1


4  

You're not converting [IsBirthdayVoucher] to VARCHAR, you're converting @var2 to VARCHAR.

您没有将[IsBirthdayVoucher]转换为VARCHAR,而是将@ var2转换为VARCHAR。

Try:

SET @sql = ('select ' + @var1 + ' + convert(varchar, ' + @var2 + ') from [VoucherType] where [DeletedBy] is null and [AutoID] = 1')

#2


0  

try this:

SET @sql = ('select CONCAT(' + @var1 + ',' + @var2 + ') from [VoucherType] where [DeletedBy] is null and [AutoID] = 1')