SELECT [...] WHERE X IN @variable

时间:2012-01-25 15:17:55

标签: sql sql-server sql-server-2008 select

  

可能重复:
  Parameterizing an SQL IN clause?

我对数据库具有只读权限,我想对其进行以下操作:

DECLARE @var AS INT_COLLECTION = (1,2,3)
SELECT name,column
FROM table
WHERE column IN @var

当然INT_COLLECTION不存在,但SQL Server 2008中是否有类似的东西?或者在没有对数据库的写访问权的情况下执行此操作的另一种方法?

2 个答案:

答案 0 :(得分:4)

这是一个非常严厉的方法,因为你必须创建一个用户定义的表类型,但它确实有效:

CREATE TYPE INT_COLLECTION AS TABLE (
  Value Int
);
GO

DECLARE @var AS INT_COLLECTION;
INSERT INTO @var (Value)
VALUES (1), (2), (3);

SELECT name, col
FROM YourTable
WHERE col IN (SELECT Value FROM @var)

答案 1 :(得分:1)

你可以这样做:

DECLARE @var AS TABLE (IDS INT);
INSERT INTO @var  VALUES (1),(2),(3);

SELECT name,column
FROM table
WHERE column IN ( SELECT IDS FROM @var)