我有以下查询,用于返回逗号分隔的结果。
SELECT STUFF
(
(
SELECT ',' + em.EMAIL
FROM(
SELECT DISTINCT USR.EMAIL AS EMAIL
FROM PRNCPLS A, PRNCPLS B, USER_INFO USR,
RELATIONSHIPS C
WHERE A.ID = C.PARENTID
AND B.ID = C.CHILDID
AND A.TYPE = 'USER' and B.TYPE = 'ROLE'
AND A.ID = USR.ID
and B.NAME = 'Approver'
AND USR.EMAIL IS NOT NULL) em
ORDER BY em.EMAIL FOR XML PATH('')
),
1, 1, ''
) AS Output
我需要以某种方式更新此查询,使得SQL语句的第一行(而不是输出)始终像这样
SELECT EMAIL FROM
这是必需的,因为出于某种原因,我使用的工具期望第一行中有FROM
,而SELECT
子句中只有一个元素。我的查询实际上只返回一个元素,所以我希望以某种方式更新它。
预期输出-abcd @ gmail.com,1234 @ yahoo.com,xyz @ gmail.com
任何帮助将不胜感激。
答案 0 :(得分:2)
您尝试过
SELECT 'SELECT EMAIL FROM ' + STUFF
(
(
SELECT ',' + em.EMAIL
FROM(
SELECT DISTINCT USR.EMAIL AS EMAIL
FROM PRNCPLS A, PRNCPLS B, USER_INFO USR,
RELATIONSHIPS C
WHERE A.ID = C.PARENTID
AND B.ID = C.CHILDID
AND A.TYPE = 'USER' and B.TYPE = 'ROLE'
AND A.ID = USR.ID
and B.NAME = 'Approver'
AND USR.EMAIL IS NOT NULL) em
ORDER BY em.EMAIL FOR XML PATH('')
),
1, 1, ''
) AS Output;
还是还有关于数据格式的更多信息?
答案 1 :(得分:2)
您是否尝试过
SELECT 'SELECT EMAIL FROM '
UNION
... Your existing query
答案 2 :(得分:2)
SELECT EMAIL FROM (
SELECT STUFF
(
(
SELECT ',' + em.EMAIL
FROM(
SELECT DISTINCT USR.EMAIL AS EMAIL
FROM PRNCPLS A, PRNCPLS B, USER_INFO USR,
RELATIONSHIPS C
WHERE A.ID = C.PARENTID
AND B.ID = C.CHILDID
AND A.TYPE = 'USER' and B.TYPE = 'ROLE'
AND A.ID = USR.ID
and B.NAME = 'Approver'
AND USR.EMAIL IS NOT NULL) em
ORDER BY em.EMAIL FOR XML PATH('')
),
1, 1, '') AS EMAIL
) AS Output
当心“ EMAIL ...”:
答案 3 :(得分:0)
您可以像这样包装几乎所有SELECT
:
SELECT t.SomeColumn FROM
(
place your existing SELECT here
) t;
这不适用于CTE查询,但是CTE本身可以转移到子查询中。
提示:如果可能,请尽量避免使用老式的联接。 Sami在评论中提供了一个很好的链接...