I have a basic SQL query, starting with:
SELECT top 20 application_id, [name], location_id FROM apps
Now, I would like to finish it so that it
One way is to split the string on the commas, strip out the spaces and insert the values into a temporary table. Then you can join your query against the temp table.
This is a T-SQL code snippet that splits a comma-separated list and inserts the members into a temporary table. Once you've populated the table you can join against it.
-- This bit splits up a comma separated list of key columns
-- and inserts them in order into a table.
--
if object_id ('tempdb..#KeyCols') is not null
drop table #KeyCols
create table #KeyCols (
,KeyCol nvarchar (100)
)
set @comma_pos = 0
set @len = len(@KeyCols)
while @len > 0 begin
set @comma_pos = charindex(',', @KeyCols)
if @comma_pos = 0 begin
set @KeyCol = @KeyCols
set @KeyCols = ''
end else begin
set @KeyCol = left (@KeyCols, @comma_pos - 1)
set @KeyCols = substring(@KeyCols,
@comma_pos + 1,
len (@KeyCols) - @comma_pos)
end
insert #KeyCols (KeyCol)
values (@KeyCol)
set @len = len (@KeyCols)
end