1

Right now my code looks like:

SELECT * 
  FROM Table 
 WHERE Id in ('123','456','789')

And I want to make the list a variable so that the code would look something like this:

Id_list = ('123','456','789')

SELECT * 
  FROM Table 
 WHERE Id in Id_list

I'm not super familiar with SQL, I'm sorry if this is obvious or my description uses the wrong terminology. Thanks!

4
  • 6
    Which dbms are you using? (SQL itself has no array variables.) Commented May 1, 2018 at 15:06
  • @jarlh: that's not entirely true. The SQL standard does define arrays Commented May 1, 2018 at 15:27
  • 1
    What DBMS are you using (MySQL, PostgreSQL, SQL Server, etc)? While an array is the SQL99 standard, not all DBMS implement it and the ones that do have slightly different flavors of it. Commented May 1, 2018 at 15:37
  • Which programming language are you using? Commented May 1, 2018 at 16:06

4 Answers 4

1

In mysql, mysql sever:

SELECT *
  FROM (SELECT '1' 
        UNION SELECT '2' 
        UNION SELECT '3' 
        UNION SELECT '4') as Array
Sign up to request clarification or add additional context in comments.

Comments

1

a possible solution is to put the array in a VARCHAR:

Id_list VARCHAR2(500)= '123,456,789';

SELECT * 
  FROM Table 
 WHERE INSTR(Id_list,Id) > 0

Regards!

Comments

0

SQL Server Version :

--Test Data
CREATE TABLE TestTable
    ([ID] nvarchar(20))
;

INSERT INTO TestTable
    ([ID])
VALUES
    ('123'),
    ('456'),
    ('789')
;

--Use With As
with arr_st as (
  select '123' ID union all
  select '456' ID union all
  select '789' ID
)
SELECT * FROM TestTable 
WHERE Id in (select * from arr_st)

Result:


SQL Fiddle LINK http://sqlfiddle.com/#!18/fbba7/2/0

Hope It help you :)

Comments

0

it's sql server method

select * into #Array  --it's sql server temp table
from (
  select '123' [value] union all
  select '456' [value] union all
  select '789' [value]
) T
;  

SELECT * FROM YourTable 
WHERE YourColumn in (select * from #Array)

use temp table like collection in sql

1 Comment

Please explain your lines of code so other users can understand its functionality. Thanks!

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.