T-SQL:如何将逗号连接到除最终记录之外的所有文本字段

时间:2016-05-21 13:25:50

标签: tsql window-functions

我想知道如何编写查询,该查询可以为所有选定的记录(最终记录除外)添加逗号到文本字段。

我想创建一个泛型函数,它可以包装查询以创建C#和TypeScript的枚举赋值语句。这是一个通用查询:

SELECT ATextField, AnIntegerField
FROM table1 join table2 .... join tableN

包装函数应返回以文本字段排序的不同值,格式如下:

TextValue1 = 15,
TextValue2 = 3,
...
TextValueN = 128 --No comma here on the final record

2 个答案:

答案 0 :(得分:1)

没有尝试,因为你没有提供任何样本数据,但可能你可以使用LEAD函数检查是否有任何后续行,如果没有你设置“逗号”:

https://msdn.microsoft.com/en-us/library/hh213125.aspx

SELECT ATextField + '=' + cast(AnIntegerField as varchar(50)) + 
case when lead(xxxxxxx add specific code here xxxxxx) then ',' else '' end
FROM table1 join table2 .... join tableN

答案 1 :(得分:0)

按照Reboon的建议,这是一个可插拔的解决方案:

WITH cte (KeyNumber, TextValue) AS (
    SELECT t1.AnIntegerField, t3.ATextField
    FROM Schema1.Table1 t1
    JOIN Schema2.Table2 t2 ON t1.JField1 = t2.JField2
    JOIN Schema3.Table3 t3 ON t2.JField1 = t3.JField2
    WHERE t1.FField1 = N'filter on this value'
)
SELECT TextValue + N' = ' + CONVERT(NVARCHAR(10), KeyNumber) + CASE WHEN (LEAD(1) OVER(ORDER BY TextValue)) IS NULL THEN N'' ELSE N',' END AS EnumAssignment
FROM (
SELECT DISTINCT TOP 100 PERCENT KeyNumber, TextValue
FROM cte
ORDER BY TextValue ) w