T-SQL stored procedure that accepts multiple Id values

后端 未结 6 932
既然无缘
既然无缘 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:39

    Yeah, your current solution is prone to SQL injection attacks.

    The best solution that I've found is to use a function that splits text into words (there are a few posted here, or you can use this one from my blog) and then join that to your table. Something like:

    SELECT d.[Name]
    FROM Department d
        JOIN dbo.SplitWords(@DepartmentIds) w ON w.Value = d.DepartmentId
    

提交回复
热议问题