T-SQL stored procedure that accepts multiple Id values

后端 未结 6 1039
既然无缘
既然无缘 2020-11-22 03:06

Is there a graceful way to handle passing a list of ids as a parameter to a stored procedure?

For instance, I want departments 1, 2, 5, 7, 20 returned by my stored

6条回答
  •  醉梦人生
    2020-11-22 03:44

    One method you might want to consider if you're going to be working with the values a lot is to write them to a temporary table first. Then you just join on it like normal.

    This way, you're only parsing once.

    It's easiest to use one of the 'Split' UDFs, but so many people have posted examples of those, I figured I'd go a different route ;)

    This example will create a temporary table for you to join on (#tmpDept) and fill it with the department id's that you passed in. I'm assuming you're separating them with commas, but you can -- of course -- change it to whatever you want.

    IF OBJECT_ID('tempdb..#tmpDept', 'U') IS NOT NULL
    BEGIN
        DROP TABLE #tmpDept
    END
    
    SET @DepartmentIDs=REPLACE(@DepartmentIDs,' ','')
    
    CREATE TABLE #tmpDept (DeptID INT)
    DECLARE @DeptID INT
    IF IsNumeric(@DepartmentIDs)=1
    BEGIN
        SET @DeptID=@DepartmentIDs
        INSERT INTO #tmpDept (DeptID) SELECT @DeptID
    END
    ELSE
    BEGIN
            WHILE CHARINDEX(',',@DepartmentIDs)>0
            BEGIN
                SET @DeptID=LEFT(@DepartmentIDs,CHARINDEX(',',@DepartmentIDs)-1)
                SET @DepartmentIDs=RIGHT(@DepartmentIDs,LEN(@DepartmentIDs)-CHARINDEX(',',@DepartmentIDs))
                INSERT INTO #tmpDept (DeptID) SELECT @DeptID
            END
    END
    

    This will allow you to pass in one department id, multiple id's with commas in between them, or even multiple id's with commas and spaces between them.

    So if you did something like:

    SELECT Dept.Name 
    FROM Departments 
    JOIN #tmpDept ON Departments.DepartmentID=#tmpDept.DeptID
    ORDER BY Dept.Name
    

    You would see the names of all of the department IDs that you passed in...

    Again, this can be simplified by using a function to populate the temporary table... I mainly did it without one just to kill some boredom :-P

    -- Kevin Fairchild

提交回复
热议问题