I would also recommend using a stored procedure, because otherwise you will leave yourself open to attack SQL injection - especially where you create a string based on user input.
Sort of:
a' or 1=1; -- Do bad things
You can use sp_executesql in SQL to run the SQL statement, which is created using the where clause such as @dcp, and although it will not optimize well, it is probably a quick command to run anyway.
Example SQL Injection Attacks
One way to achieve this is to use charindex. This example shows how to run a stored procedure when passing a list of identifiers separated by spaces:
declare @machine table (machineId int, machineName varchar(20)) declare @files table (fileId int, machineId int) insert into @machine (machineId, machineName) values (1, 'machine') insert into @machine (machineId, machineName) values (2, 'machine 2.0') insert into @machine (machineId, machineName) values (3, 'third machine') insert into @machine (machineId, machineName) values (4, 'machine goes forth') insert into @machine (machineId, machineName) values (5, 'machine V') insert into @files (fileId, machineId) values (1, 3) insert into @files (fileId, machineId) values (2, 3) insert into @files (fileId, machineId) values (3, 2) insert into @files (fileId, machineId) values (4, 1) insert into @files (fileId, machineId) values (5, 3) insert into @files (fileId, machineId) values (6, 5) declare @machineText1 varchar(100) declare @machineText2 varchar(100) declare @machineText3 varchar(100) set @machineText1 = '1 3 4' set @machineText2 = '1' set @machineText3 = '5 6' select * from @files where charindex(rtrim(machineId), @machineText1, 1) > 0
Thus, you can create this stored procedure to achieve your goal:
create procedure FilesForMachines (@machineIds varchar(1000)) as select * from [Files] where charindex(rtrim(machineId), @machineIds, 1) > 0
Charindex tip from BugSplat .