拼接带分隔符字符串的细节

我最近见到有同事这样拼接字符串(SQL Server 2008 R2,CTE部分是伪造的示例数据)

 1 WITH TEMP AS
2 (
3 SELECT 'A' AS ITEM
4 UNION ALL
5 SELECT 'B' AS ITEM
6 UNION ALL
7 SELECT 'C' AS ITEM
8 )
9 SELECT A.ITEM+',' AS [data()]
10 FROM TEMP A
11 FOR XML PATH('')

这个QUERY会得到这样的XML

A, B, C,

但是潜在的问题是当数据不是字符型的时候会出问题,试把CTE中的数据全部改为数字

WITH TEMP AS
(
SELECT 1 AS ITEM
UNION ALL
SELECT 2 AS ITEM
UNION ALL
SELECT 3 AS ITEM
)
SELECT A.ITEM+',' AS [data()]
FROM TEMP A
FOR XML PATH('')

这个QUERY会报错:

Msg 245, Level 16, State 1, Line 2 Conversion failed when converting the varchar value ',' to data type int.

所以,我推荐的拼接方式是

WITH TEMP AS
(
SELECT 1 AS ITEM
UNION ALL
SELECT 2 AS ITEM
UNION ALL
SELECT 3 AS ITEM
)
SELECT A.ITEM AS [data()],','
FROM TEMP A
FOR XML PATH('')

运行结果是:

1,2,3,

点击这里加入SQL Server精英群

你可能感兴趣的:(拼接带分隔符字符串的细节)