1

So I have the two queries below.

The first query works however in my where condition I've hard coded some values. So in the second query I've put the same values but declared them as variables. However when I run it nothing is returned, which I don't understand?

First Query

declare @fxPair nvarchar(max) = ''
select @fxPair = @fxPair + '[' + Currency + '], ' 
from myTbl  
where DateH = '2016-11-14' and Code in ('ABV', 'ABG')
group by Currency
order by Currency   
set @fxPair = SUBSTRING(@fxPair, 1, len(@fxPair) - 1)
print @fxPair

Second Query

declare @Code nvarchar(10) = 'ABV, ABG'
declare @DateH nvarchar(20) = '2016-11-14'

declare @fxPair nvarchar(max) = ''
select @fxPair = @fxPair + '[' + Currency + '], ' 
from myTbl  
where DateH = @DateH and Code in (@Code)                -- this line doesn't work
group by Currency
order by Currency   
set @fxPair = SUBSTRING(@fxPair, 1, len(@fxPair) - 1)
print @fxPair
8
  • I'm not sure what your question is. With a single variable, in is the same as =, so your code is really code = @code. And a single code isn't going to match a list. Commented Nov 25, 2016 at 14:42
  • 2
    'ABV, ABG' is very different to {'ABV', 'ABG'} Commented Nov 25, 2016 at 14:42
  • @GordonLinoff, sorry that was a typo. Code = 'ABV, ABG' Commented Nov 25, 2016 at 14:48
  • @JuanCarlosOropeza sorry what is the difference? Commented Nov 25, 2016 at 14:49
  • 2
    One is a string, the other is an array/list. IN will compare the whole string, wont separate the values. Commented Nov 25, 2016 at 14:50

1 Answer 1

3

you can try it like this :

declare @code table (code varchar(10))
declare @DateH nvarchar(20) = '2016-11-14'
declare @fxPair nvarchar(max) = ''

insert into @code values ('ABV'), ('ABG')

select @fxPair = @fxPair + '[' + Currency + '], ' 
from   myTbl  
where  DateH = @DateH 
and    Code in (select code from @code)
group by Currency
order by Currency   

set @fxPair = SUBSTRING(@fxPair, 1, len(@fxPair) - 1)
print @fxPair
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.