1

I want to store some id's in a variable then to use this variable multiple times wherever I have to use in queries. I used this format as:

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

But this gives me the result only for any single ID from a list of ID's as I used query to retrieve multiple ID's from table sub_aminer_paper.

Please help and Thanks!

3
  • Create a temp table and store the results in it and then do the select. INT can not store more than one value. Commented Sep 21, 2015 at 10:47
  • Or a table variable or use this variable inside a while loop. Commented Sep 21, 2015 at 11:14
  • See sommarskog.se/arrays-in-sql.html. Commented Sep 21, 2015 at 12:14

2 Answers 2

1

What you want is a table variable:

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)
Sign up to request clarification or add additional context in comments.

Comments

1

You could also do this without using a variable, with something like this:

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)

1 Comment

Or do the same thing using a CTE or derived table

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.