Reputation: 766
I am trying to print a particular column from a table in a message to the user. Here's the table example
StateCode | EffectiveDate | ExpirationDate
---------------------------------------------
AK | 2011-12-31 | 2012-12-31
AL | 2011-12-31 | 2015-12-31
and so on for all states. What I'd like to do is select that the GETDATE() is not between the EffectiveDate and ExpirationDate and print a message to the user. The Select Statement I have works but if more than one state is returned it crashes. Any way to save a list and then print that? or another approach I can take
Heres the Select Query I am using now that works for 1 state returned
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
Thanks for any Help
Upvotes: 6
Views: 26561
Reputation: 204924
To get a comma seperated list of states do:
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
Upvotes: 1
Reputation: 39807
You have to combine multiple values into a single variable:
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
Upvotes: 3