Table-Valued User-Defined Function
Another method is to create a user-defined function that will convert the comma
separated value into a table that can then be used to join with the
[dbo].[Lawyers] table. Below is a table-valued user-defined function that
takes a comma-delimited value and returns a table containing these values.
CREATE FUNCTION [dbo].[ufn_CSVToTable] ( @StringInput VARCHAR(8000) )
RETURNS @OutputTable TABLE ( [String] VARCHAR(10) )
AS
BEGIN
DECLARE @String VARCHAR(10)
WHILE LEN(@StringInput) > 0
BEGIN
SET @String = LEFT(@StringInput,
ISNULL(NULLIF(CHARINDEX(',', @StringInput) - 1, -1),
LEN(@StringInput)))
SET @StringInput = SUBSTRING(@StringInput,
ISNULL(NULLIF(CHARINDEX(',', @StringInput), 0),
LEN(@StringInput)) + 1, LEN(@StringInput))
INSERT INTO @OutputTable ( [String] )
VALUES ( @String )
END
RETURN
END
GO
To use it in the stored procedure that retrieves the lawyers, here's how it will
look like:
CREATE PROCEDURE [dbo].[GetLawyers] ( @ZIP CHAR(5), @LawyerTypeIDs VARCHAR(100) )
AS
SELECT Lawyer.*
FROM [dbo].[Lawyers] Lawyer INNER JOIN [dbo].[ufn_CSVToTable] ( @LawyerTypeIDs ) LawyerType
ON Lawyer.[LawyerTypeID] = LawyerType.[String]
WHERE Lawyer.[ZIP] = @ZIP
GO
Executing the stored procedure is the same way as the previous method:
EXECUTE [dbo].[GetLawyers] '12345', '1,4'