选择查询,变量不返回正确的结果

时间:2016-11-25 14:41:49

标签: sql-server tsql

所以我在下面有两个问题。

然而,第一个查询在我的条件下工作,我已经硬编码了一些值。所以在第二个查询中我放了相同的值但是将它们声明为变量。但是当我运行它时没有返回任何内容,我不明白?

首次质询

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

第二次查询

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

1 个答案:

答案 0 :(得分:3)

你可以这样试试:

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