2012-08-02 67 views
4

我试图从消息中的表格中向用户打印特定列。 下面是表格示例SQL,从选择查询中打印一列

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

等等所有状态。我想要做的是选择GETDATE()不在EffectiveDate和ExpirationDate之间并向用户输出消息。选择语句我有效,但如果返回多个状态,它会崩溃。任何方式来保存列表,然后打印?或者另一种方法,我可以采取

继承人我现在使用的是适用于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 

感谢任何帮助

回答

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 
+0

谢谢你正是我想找的。 – 2012-08-02 17:05:07

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