Home Forums SQL Server 2008 SQL Server 2008 - General Passing comma separated values for IN list in DELETE statement from SQLCMD RE: Passing comma separated values for IN list in DELETE statement from SQLCMD

  • Alright, finally home and can spend a little time on this. First, get your hands on a copy of the function DelimitedSplit8k from here: http://www.sqlservercentral.com/articles/Tally+Table/72993/

    Read the article as well, please. You'll have to get acquainted with the Tally Table as well. These can be some more advanced topics but the short version is if you copy/paste the code and feed it a string with comma delimited values it'll hand you back a 'table' of those values as a single column. My usual disclaimer here: If you don't understand the code you're putting in production, DON'T.

    Anyways, that said, once you get a handle on it, you'll usually have a proc that looks a little like this before you start and it won't work because IN won't take your variable:

    CREATE PROC GetData

    @SplitmeString VARCHAR(8000)

    AS

    SELECT

    st.*

    FROM

    SomeTable AS st

    WHERE

    st.ID IN (@SplitmeString)

    GO

    Call would be something like:

    EXEC GetData @SplitmeString = '1,2,4,8,16,32,64'

    So, with our new handy-dandy function, now our proc will look like this:

    CREATE PROC GetData

    @SplitmeString VARCHAR(8000)

    AS

    SELECT

    st.*

    FROM

    SomeTable AS st

    JOIN

    DelimitedSplit8K( @SplitmeString, ',') AS dsk

    ONst.ID = dsk.Item

    GO

    So, what have we really done? Basic SQL: An INNER JOIN restricts row data coming from both sides via the ON clause. Because your list (even if it only had one element) is now restricting to only the IDs you want, the JOIN takes the place of the WHERE. The function returns a table from your string, and thus will allow you to use it that way.

    This gets around the entire problem of trying to dynamically construct code to allow your delimited string to be included in the query.


    - Craig Farrell

    Never stop learning, even if it hurts. Ego bruises are practically mandatory as you learn unless you've never risked enough to make a mistake.

    For better assistance in answering your questions[/url] | Forum Netiquette
    For index/tuning help, follow these directions.[/url] |Tally Tables[/url]

    Twitter: @AnyWayDBA