如何声明包含多个整数值SQL Server的变量

时间:2015-09-21 10:45:34

标签: arrays sql-server variables

我想在变量中存储一些id,然后在我必须在查询中使用的地方多次使用此变量。我使用这种格式:

DECLARE @aid INT
SELECT @aid = AP.aid
FROM 
    sub_aminer_paper AP
GROUP BY 
    AP.aid
HAVING 
    MIN(p_year) = 1990 AND MAX(AP.p_year) = 2014 AND COUNT(AP.pid) BETWEEN 10 AND 40

SELECT 
    * 
FROM 
    sub_aminer_paper 
WHERE 
    aid = @aid

但是这只给了我ID ID列表中任何一个ID的结果,因为我使用查询从表sub_aminer_paper中检索多个ID。

请帮忙,谢谢!

2 个答案:

答案 0 :(得分:1)

你想要的是http://www.codeigniter.com/user_guide/installation/upgrade_300.html?highlight=any#routes-containing-any

DECLARE @aid TABLE(id INT PRIMARY KEY)

INSERT INTO @aid
SELECT AP.aid
FROM sub_aminer_paper AP
GROUP BY AP.aid
HAVING 
    MIN(p_year) = 1990
    AND MAX(AP.p_year) = 2014
    AND COUNT(AP.pid) BETWEEN 10 AND 40

SELECT * 
FROM sub_aminer_paper 
WHERE 
    aid = (SELECT id FROM @aid)

答案 1 :(得分:1)

您也可以在不使用变量的情况下执行此操作,如下所示:

SELECT * 
FROM sub_aminer_paper AP1
where exists (
  SELECT 1
  FROM sub_aminer_paper AP2
  WHERE AP1.aid = AP2.aid
  GROUP BY AP2.aid
  HAVING 
    MIN(AP2.p_year) = 1990
    AND MAX(AP2.p_year) = 2014
    AND COUNT(AP2.pid) BETWEEN 10 AND 40)