How to pass an array into a SQL Server stored procedure

前端 未结 11 2418
轻奢々
轻奢々 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-21 23:42

    Based on my experience, by creating a delimited expression from the employeeIDs, there is a tricky and nice solution for this problem. You should only create an string expression like ';123;434;365;' in-which 123, 434 and 365 are some employeeIDs. By calling the below procedure and passing this expression to it, you can fetch your desired records. Easily you can join the "another table" into this query. This solution is suitable in all versions of SQL server. Also, in comparison with using table variable or temp table, it is very faster and optimized solution.

    CREATE PROCEDURE dbo.DoSomethingOnSomeEmployees  @List AS varchar(max)
    AS
    BEGIN
      SELECT EmployeeID 
      FROM EmployeesTable
      -- inner join AnotherTable on ...
      where @List like '%;'+cast(employeeID as varchar(20))+';%'
    END
    GO
    

提交回复
热议问题