How to pass an array into a SQL Server stored procedure

前端 未结 11 2458
轻奢々
轻奢々 2020-11-21 23:28

How to pass an array into a SQL Server stored procedure?

For example, I have a list of employees. I want to use this list as a table and join it with another table.

11条回答
  •  死守一世寂寞
    2020-11-22 00:04

    It took me a long time to figure this out, so in case anyone needs it...

    This is based on the SQL 2005 method in Aaron's answer, and using his SplitInts function (I just removed the delim param since I'll always use commas). I'm using SQL 2008 but I wanted something that works with typed datasets (XSD, TableAdapters) and I know string params work with those.

    I was trying to get his function to work in a "where in (1,2,3)" type clause, and having no luck the straight-forward way. So I created a temp table first, and then did an inner join instead of the "where in". Here is my example usage, in my case I wanted to get a list of recipes that don't contain certain ingredients:

    CREATE PROCEDURE dbo.SOExample1
        (
        @excludeIngredientsString varchar(MAX) = ''
        )
    AS
        /* Convert string to table of ints */
        DECLARE @excludeIngredients TABLE (ID int)
        insert into @excludeIngredients
        select ID = Item from dbo.SplitInts(@excludeIngredientsString)
    
        /* Select recipies that don't contain any ingredients in our excluded table */
       SELECT        r.Name, r.Slug
    FROM            Recipes AS r LEFT OUTER JOIN
                             RecipeIngredients as ri inner join
                             @excludeIngredients as ei on ri.IngredientID = ei.ID
                             ON r.ID = ri.RecipeID
    WHERE        (ri.RecipeID IS NULL)
    

提交回复
热议问题