我想编写一个函数,用于通过id从不同的行和组中连接字段 当我在TSql中执行我的代码工作正常,但当我作为一个函数执行它时,它返回错误的数据,为什么?
CREATE TABLE YourTable ([ID] INT, [Name] CHAR(1), [Value] INT)
INSERT INTO YourTable ([ID],[Name],[Value]) VALUES (1,'A',4)
INSERT INTO YourTable ([ID],[Name],[Value]) VALUES (1,'B',8)
INSERT INTO YourTable ([ID],[Name],[Value]) VALUES (2,'C',9)
INSERT INTO YourTable ([ID],[Name],[Value]) VALUES (3,'d',9)
INSERT INTO YourTable ([ID],[Name],[Value]) VALUES (3,'u',9)
SELECT
[ID],
STUFF((
SELECT ', ' + [Name]
FROM YourTable
WHERE (ID = Results.ID)
FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)'),1,2,'') AS NameValues
FROM YourTable Results
GROUP BY id;
create FUNCTION dbo.CONCAT_String_group_by_id (@id int , @name varchar
(100) )
RETURNS TABLE AS return
WITH cte AS(
SELECT @id id ,@name name
FROM (VALUES(0)) a(m))
SELECT
[ID],
STUFF((
SELECT ', ' + [Name]
FROM cte
WHERE (ID = Results.ID)
FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)'),1,2,'') AS NameValues
FROM cte Results
GROUP BY id
SELECT n.*
FROM YourTable CROSS APPLY dbo.CONCAT_String_group_by_id (id,name) n
首先查询输出:
ID NameValues
1 A, B
2 C
3 d, u
第二次查询输出:
ID NameValues
1 A
1 B
2 C
3 d
3 u
答案 0 :(得分:1)
您的功能不起作用,因为将对外部查询的每一行执行Cross apply并输出结果
在您的第一个查询中,您正在一次评估所有数据,执行的逻辑顺序如下所示
查询:
SELECT
[ID],
STUFF((
SELECT ', ' + [Name]
FROM YourTable
WHERE (ID = Results.ID)
FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)'),1,2,'') AS NameValues
FROM YourTable Results
GROUP BY id;
1.来自你桌子的id分组 2.使用XML
进行所有ID的连续在您的第二个查询中,您使用交叉应用一次传递一行,并且只有一行要连接,因此您的输出会有所不同
答案 1 :(得分:0)
这个功能怎么样:
archetype:generate
在你的功能中,你的CTE中只有一行(CREATE FUNCTION dbo.CONCAT_String_group_by_id (@id int)
RETURNS TABLE AS return
WITH cte AS(
SELECT *
FROM YourTable
WHERE id = @id
)
SELECT
[ID],
STUFF((
SELECT ', ' + [Name]
FROM cte
WHERE (ID = Results.ID)
FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)'),1,2,'') AS NameValues
FROM cte Results
GROUP BY id
)所以你总是在WITH
中有一个字母。