0

I have a query that produces the following resultset:

ID (text)    VAL
 1           A
 2           B
 3           C

I want to generate a WHERE clause from the resultset IDs:

where id in ('1','2','3')

With Oracle, I can use the following query to generate a WHERE clause:

with a as (

  <my_query>

)
select 'where id in ('
  || listagg(id, ',') within group(order by id)
  || ')' as where_clause
from a

Is there a way to do the same sort of thing using SQL Server?


Related: Oracle: Generate WHERE clause from resultset ids?

User1974
  • 276
  • 1
  • 17
  • 63
  • [STRING_AGG()](https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-ver15) – Squirrel Nov 25 '21 at 06:01

2 Answers2

1

Just try this.

with a as (

  <my_query>

)
SELECT 'WHERE id IN (' +
  STRING_AGG(id, ',') WITHIN GROUP(ORDER BY id) 
  + ')' as where_clause
FROM a

then you will get WHERE id IN (1,2,3)

If you want to get WHERE id IN ('1','2','3') then you can change like following

SELECT 'WHERE id IN (''' +
      STRING_AGG(id, ''',''') WITHIN GROUP(ORDER BY id) 
      + ''')' as where_clause
FROM a
Web Star
  • 431
  • 3
  • 20
0

You can just use a normal IN

with a as (

  <my_query>

),
b as (

  <Other Query>

)
select *
from b
where b.id in (
  select a.id
  from a
);
Charlieface
  • 52,284
  • 6
  • 19
  • 43