SQL 服务器:从结果集 ID 生成 WHERE 子句?

SQL Server: Generate WHERE clause from resultset ids?

我有一个生成以下结果集的查询:

ID (text)    VAL
 1           A
 2           B
 3           C

我想从结果集 ID 生成 WHERE 子句:

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

对于 Oracle,我可以使用以下查询生成 WHERE 子句:

with a as (

  <my_query>

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

有没有办法使用 SQL 服务器做同样的事情?


相关:

试试这个。

with a as (

  <my_query>

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

那么你会得到WHERE id IN (1,2,3)

如果你想得到WHERE id IN ('1','2','3') 然后你可以像下面这样改变

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

你可以使用普通的IN

with a as (

  <my_query>

),
b as (

  <Other Query>

)
select *
from b
where b.id in (
  select a.id
  from a
);