SQL Server procedure declare a list

后端 未结 6 645
粉色の甜心
粉色の甜心 2020-12-24 05:28

My SQL code is fairly simple. I\'m trying to select some data from a database like this:

SELECT * FROM DBTable
WHERE id IN (1,2,5,7,10)

I w

6条回答
  •  借酒劲吻你
    2020-12-24 05:57

    You could declare a variable as a temporary table like this:

    declare @myList table (Id int)
    

    Which means you can use the insert statement to populate it with values:

    insert into @myList values (1), (2), (5), (7), (10)
    

    Then your select statement can use either the in statement:

    select * from DBTable
    where id in (select Id from @myList)
    

    Or you could join to the temporary table like this:

    select *
    from DBTable d
    join @myList t on t.Id = d.Id
    

    And if you do something like this a lot then you could consider defining a user-defined table type so you could then declare your variable like this:

    declare @myList dbo.MyTableType
    

提交回复
热议问题