Be careful with the code in the article. Be aware that it doesn't do full validation. It only evaluates what's right and give no indication as to what is wrong. If that's good for you, so be it (although I believe there are better ways). Just make sure it's good for you. 😉
The following example has been copied from the article code. "XX" has been added to the parameter. See for yourself that "XX" produces no error and no alert because "XX" isn't even considered in the validation.
-- Imagine this table exists previously in your database ----
Declare @T_STATES table ( state char(2) )
Insert @T_STATES Values ( 'AZ' )
Insert @T_STATES Values ( 'CA' )
Insert @T_STATES Values ( 'MT' )
Insert @T_STATES Values ( 'TX' )
Insert @T_STATES Values ( 'WA' )
Insert @T_STATES Values ( 'TS' )
-- Suppose this is the parameter ----
Declare @sParameter varchar(8000)
Set @sParameter = 'WA,AZ,CA,TS,XX' --<<< Code doesn't catch the invalid parameter
Declare @tStates table ( state char(2) )
Insert @tStates
Select state
From @T_STATES
Where CharIndex( state, @sParameter ) > 0
Select *
From @tStates
Even the final bit of code doesn't catch the fact that an invalid element was passed...
-- Imagine this table exists previously in your database ----
Declare @T_STATES table ( state char(2) )
Insert @T_STATES Values ( 'AZ' )
Insert @T_STATES Values ( 'CA' )
Insert @T_STATES Values ( 'MT' )
Insert @T_STATES Values ( 'TX' )
Insert @T_STATES Values ( 'WA' )
Insert @T_STATES Values ( 'TS' )
-- Suppose this is the parameter ----
Declare @sParameter varchar(8000)
Set @sParameter = 'WA,AZ,CA,TS,XX' --<<< Code doesn't catch the invalid parameter
Declare @tStates table ( state char(2) )
Insert @tStates
Select state
From @T_STATES
Where CharIndex( state, @sParameter ) > 0
If @@RowCount < 1
Begin
Select 'No matches. Valid values are:' As InfoMessage
Union All
Select state
From @T_STATES
Return
End
--Jeff Moden
Change is inevitable... Change for the better is not.