Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert list of values in SQL to CTE or Temp Table

Tags:

sql

sql-server

How can I convert a list of values like (value1, value2, value3, ...., value500) to a temp table or cte?

One way would be to do:

WITH huge_list_cte AS (
   Select value1
   UNION
   Select value2 ...
)

Is there a better way?

like image 421
AnotherDeveloper Avatar asked Sep 06 '25 20:09

AnotherDeveloper


2 Answers

Use values:

WITH huge_list_cte AS (
      SELECT v
      FROM (VALUES (value1), (value2), . . . ) v(v)
     )
. . .
like image 155
Gordon Linoff Avatar answered Sep 08 '25 11:09

Gordon Linoff


You can use table variable

DECLARE @Data TABLE(Id INT);
INSERT INTO @Data VALUES (101), (102) ...

Then you can use it in your queries as normal table

SELECT * FROM @Data

You can even create predefined table type and reuse it Microsoft Docs: table

like image 30
Fabio Avatar answered Sep 08 '25 10:09

Fabio