What database are you using? in SQL Server, you can create a split function that can split a long string and return a subsecond table. you use a table function call like a regular table in a query (no temp table needed)
You need to create a split function, or if you just use it. Here's how to use the split function:
SELECT * FROM YourTable y INNER JOIN dbo.yourSplitFunction(@Parameter) s ON y.ID=s.Value
I prefer the number table approach to split strings in TSQL , but there are many ways to split strings in SQL Server, see the previous link that explains the PRO and CON of each of them.
For the Numbers Table method to work, you need to perform this setting of a single time table that will create a Numbers table that contains rows from 1 to 10000:
SELECT TOP 10000 IDENTITY(int,1,1) AS Number INTO Numbers FROM sys.objects s1 CROSS JOIN sys.objects s2 ALTER TABLE Numbers ADD CONSTRAINT PK_Numbers PRIMARY KEY CLUSTERED (Number)
Once the Numbers table is configured, create this split function:
CREATE FUNCTION [dbo].[FN_ListToTable] ( @SplitOn char(1) --REQUIRED, the character to split the @List string on ,@List varchar(8000)--REQUIRED, the list to split apart ) RETURNS TABLE AS RETURN ( ---------------- --SINGLE QUERY-- --this will not return empty rows ---------------- SELECT ListValue FROM (SELECT LTRIM(RTRIM(SUBSTRING(List2, number+1, CHARINDEX(@SplitOn, List2, number+1)-number - 1))) AS ListValue FROM ( SELECT @SplitOn + @List + @SplitOn AS List2 ) AS dt INNER JOIN Numbers n ON n.Number < LEN(dt.List2) WHERE SUBSTRING(List2, number, 1) = @SplitOn ) dt2 WHERE ListValue IS NOT NULL AND ListValue!='' ); GO
Now you can easily split the CSV row into a table and join it:
select * from dbo.FN_ListToTable(',','1,2,3,,,4,5,6777,,,')
CONCLUSION:
ListValue ----------------------- 1 2 3 4 5 6777 (6 row(s) affected)
You can use a CSV row like this rather than a temp table:
SELECT * FROM tblMyTable INNER JOIN WHERE ItemID IN (select ListValue from dbo.FN_ListToTable(',',$MyList));