If you want to get complex you can convert the input string into a temp table/table variable and then do a series of IF statements or queries at your leisure.
SQLServer proc to take a comma delimited input string and return it as a table variable.
IF EXISTS(SELECT name FROM sysobjects WHERE name = 'fn_parseString' AND (type = 'TF' OR type = 'IF' OR type = 'FN'))
DROP FUNCTION fn_parseString
GO
/* This function takes a comma delimited string of information and parses it based on commas, returning the resultant strings. */
CREATE FUNCTION fn_parseString
(@StringToParse TEXT)
RETURNS @StringTable TABLE (ParsedString VARCHAR(8000), StringIndex INT)
AS
BEGIN
DECLARE @CurrentString VARCHAR(8000)
DECLARE @CurrentStringIndex INT
DECLARE @TextLength INT
DECLARE @Index INT
DECLARE @Letter VARCHAR(1)
DECLARE @PreviousLetter VARCHAR(1)
SET @CurrentString = ''
SET @CurrentStringIndex = 0
SET @TextLength = DATALENGTH(@StringToParse)
SET @PreviousLetter = ''
SET @Index = 1
WHILE @Index <= @TextLength
BEGIN
SET @Letter = SUBSTRING(@StringToParse, @Index, 1)
IF @Letter = ','
BEGIN
SET @CurrentStringIndex = @CurrentStringIndex + 1
INSERT INTO @StringTable
(ParsedString,
StringIndex)
VALUES (@CurrentString,
@CurrentStringIndex)
IF @@ERROR <> 0
BEGIN
DELETE
FROM @StringTable
RETURN
END
SET @CurrentString = ''
END
ELSE IF @PreviousLetter <> ',' OR (@PreviousLetter = ',' AND @Letter <> ' ') /* Get rid of the spaces inserted when the string was created. */
BEGIN
SET @CurrentString = @CurrentString + @Letter
END
SET @PreviousLetter = @Letter
SET @Index = @Index + 1
END
IF @CurrentString <> ''
BEGIN
SET @CurrentStringIndex = @CurrentStringIndex + 1
INSERT INTO @StringTable
(ParsedString,
StringIndex)
VALUES (@CurrentString,
@CurrentStringIndex)
IF @@ERROR <> 0
BEGIN
DELETE
FROM @StringTable
RETURN
END
END
RETURN
END
Code to access the function elsewhere:
DECLARE @CommaDelimitedString VARCHAR(8000)
SET @CommaDelimitedString = '1,2,3,4,5,6,7,8,cow,dog,horse'
DECLARE @StringTable TABLE
(StringValue VARCHAR(8000),
ColumnID INT)
SET NOCOUNT ON
INSERT INTO @StringTable
(StringValue,
ColumnID)
SELECT ParsedString,
StringIndex
FROM dbo.fn_ParseString(@CommaDelimitedString)
IF @@ERROR <> 0
BEGIN
SET NOCOUNT OFF
RAISERROR('An error occurred while parsing the AccountIDs out of the string.',16,1)
END
SELECT * FROM [Sometable] JOIN @StringTable AS tmp ON [sometable.value] = tmp.StringValue