SQL Server:从结果集ID生成WHERE子句?
我有一个查询,它会生成以下结果集:
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 Server做同样的事情?
相关:Oracle: Generate WHERE clause from resultset ids?
解决方案
试试这个。
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
相关文章