4

我正在尝试在给用户的消息中从表中打印特定列。这是表格示例

StateCode  |   EffectiveDate   |   ExpirationDate
---------------------------------------------
  AK       |   2011-12-31      |   2012-12-31
  AL       |   2011-12-31      |   2015-12-31

依此类推,适用于所有州。我想做的是选择 GETDATE() 不在 EffectiveDate 和 ExpirationDate 之间,并向用户打印一条消息。我的 Select 语句有效,但如果返回多个状态,它会崩溃。有什么办法可以保存列表然后打印出来?或者我可以采取的另一种方法

这是我现在使用的选择查询,适用于返回的 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

谢谢你的帮助

4

2 回答 2

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
于 2012-08-02T17:01:08.950 回答
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
于 2012-08-02T17:01:21.773 回答