This is an old question, but I came up with an elegant solution for this that I like to reuse, and I think everyone else will find it useful.
First of all, you need to create a FUNCTION in SqlServer, which takes delimited input and returns a table with elements divided by records.
Here is the code for this:
ALTER FUNCTION [dbo].[Split] ( @RowData nvarchar(max), @SplitOn nvarchar(5) = ',' ) RETURNS @RtnValue table ( Id int identity(1,1), Data nvarchar(100) ) AS BEGIN Declare @Cnt int Set @Cnt = 1 While (Charindex(@SplitOn,@RowData)>0) Begin Insert Into @RtnValue (data) Select Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1))) Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData)) Set @Cnt = @Cnt + 1 End Insert Into @RtnValue (data) Select Data = ltrim(rtrim(@RowData)) Return END
Now you can do something like this:
Select Id, Data from dbo.Split('123,234,345,456',',')
And fear not, it may not be susceptible to Sql injection attacks.
Then write a stored procedure that takes comma-delimited data, and then you can write a sql statement that uses this Split function:
CREATE PROCEDURE [dbo].[findDuplicates] @ids nvarchar(max) as begin select ID from SomeTable with (nolock) where ID in (select Data from dbo.Split(@ids,',')) end
Now you can write a C # wrapper around:
public void SomeFunction(List<int> ids) { var idsAsDelimitedString = string.Join(",", ids.Select(id => id.ToString()).ToArray()); // ... or however you make your connection var con = GetConnection(); try { con.Open(); var cmd = new SqlCommand("findDuplicates", con); cmd.Parameters.Add(new SqlParameter("@ids", idsAsDelimitedString)); var reader = cmd.ExecuteReader(); // .... do something here. } catch (Exception) { // catch an exception? } finally { con.Close(); } }