我正在尝试将消息中的表中的特定列打印给用户。 这是表格示例
StateCode | EffectiveDate | ExpirationDate
---------------------------------------------
AK | 2011-12-31 | 2012-12-31
AL | 2011-12-31 | 2015-12-31
所有州的等等。我想要做的是选择GETDATE()不在EffectiveDate和ExpirationDate之间并向用户输出消息。 Select语句我有效但如果返回多个状态则会崩溃。有什么方法可以保存列表然后打印出来吗?或者我可以采取的另一种方法
继承我现在使用的Select Query,它适用于1状态返回
DECLARE @missingStates varChar(30)
SET @missingStates = Select StateCode FROM StateTable
WHERE GETDATE() NOT Between StateTable.EffectiveDate AND StateTable.ExpirationDate
PRINT 'States Missing Effective Models'
PRINT @missingStates
感谢您的帮助
答案 0 :(得分:2)
您必须将多个值组合成一个变量:
DECLARE @missingStates varChar(30)
SET @missingStates = ''
Select @missingStates = @missingStates + Code + ' ' FROM StateTable
WHERE GETDATE() NOT Between StateTable.EffectiveDate AND StateTable.ExpirationDate
PRINT 'States Missing Effective Models'
PRINT @missingStates
答案 1 :(得分:1)
要获得逗号分隔的状态列表,请执行以下操作:
Select case when @missingStates = ''
then @missingStates = Code
else @missingStates = @missingStates + ',' + Code
end as states
FROM StateTable
WHERE GETDATE() NOT Between StateTable.EffectiveDate AND StateTable.ExpirationDate