views:

671

answers:

4

Is it possible to send a list of IDs to a stored procedure from c# without dirty hacks?

UPDATE Germs
SET Mutated = ~Mutated
WHERE (GermID IN (ids))
A: 

According to This article, you could try the Table Value Parameter.

borisCallens
This is SQL Server 2008 specific I believe.
Ben Hoffstein
A: 

Yep, you can use a chunk of XML to build your list of ID's. Then you can use OPENXML and select from that record set.

Look up OPENXML, sp_preparexmldocument, sp_removexmldocument

Nick
+2  A: 

This may be a dirty hack, but you can create a temp table and then join to it from within your stored procedure (assuming they are accessed during the same connection). For example:

CREATE TABLE #ids (id int)
INSERT INTO #ids VALUES ('123') -- your C# code would generate all of the inserts

-- From within your stored procedure...
UPDATE g
SET Mutated = ~Mutated
FROM Germs g
JOIN #ids i ON g.GermID = i.id
Ben Hoffstein
+2  A: 

You could try what i have made do with:-

Create a function called Split_String

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

CREATE FUNCTION [dbo].[Split_String] 
(   
    @MyString varchar(5000)
)
RETURNS @Results TABLE
(
    Value varchar(1000)
) 
AS
    BEGIN
        DECLARE @Pos int
        DECLARE @StrLen int
        DECLARE @MyLen int
        DECLARE @MyVal varchar
        SET @pos = 1
        SET @MyLen = 1
        WHILE @MyString <> ''
            BEGIN
                SET @MyLen = charindex(',',@MyString)   
                IF @MyLen = 0 SET @MyLen = Len(@MyString)
                INSERT @Results SELECT replace(substring(@MyString, @pos, @MyLen),',','')
                SET @MyString = SUBSTRING(@MyString,@MyLen+1,len(@MyString))
            END
        RETURN 
    END

Then when you use IN() use in the following fashion with a comma separated string:-

SELECT * FROM [youDataBase].[dbo].[Split_String] (<@MyString, varchar(5000),>)
Kevin Dark
I used this a lot in SQL2005, I found the CLR functions split the string faster, but as they were opaque overall performance suffered due to bad query plans.
Meff