Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL server + dynamic query + 'The data types nvarchar and bit are incompatible in the add operator.'

Tags:

sql-server

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.

@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.

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)
like image 765
k80sg Avatar asked Dec 10 '11 08:12

k80sg


2 Answers

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

Try:

SET @sql = ('Select ' + @var1 + ' + Convert(varchar, ' + @var2 + ') 
             From [VoucherType] 
             Where [DeletedBy] is Null AND [AutoID] = 1')
like image 187
ta.speot.is Avatar answered Sep 25 '22 23:09

ta.speot.is


try this:

SET @sql = ('Select CONCAT(' + @var1 + ',' + @var2 + ') 
             From VoucherType 
             Where DeletedBy is Null and [AutoID] = 1')
like image 34
Vahid Beyranvand Avatar answered Sep 22 '22 23:09

Vahid Beyranvand