1. 程式人生 > >SQL語句中把多條記錄同一欄位的值連線成一個字串顯示結果集(sql stuff)

SQL語句中把多條記錄同一欄位的值連線成一個字串顯示結果集(sql stuff)

SELECT STUFF('abcdef', 2, 3, 'ijklmn');

結果:aijklmndf。

1.

if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([Inv] int,[order] varchar(4))
insert [tb]
select 10001,'P111' union all
select 10001,'P112' union all
select 10001,'P113' union all
select 10002,'P114' union all
select 10002,'P115'
--------------開始查詢--------------------------
select inv, [order]=stuff((select ','+[order] from tb t where Inv=tb.Inv for xml path('')), 1, 1, '')
from tb
group by Inv

select id1, [id3]=stuff((select ','+id3 from id_t t where id1=id_t.id1 for xml path('')), 1, 1, '')
from id_t GROUP BY id1

2.

001 00101    20
001 00101    80
001 00101    75
002 00101    20
002 00101    10
003 00101    70
004 00101    70
004 00101    70
004 00101    70
id1 id2 id3

if object_id('f_str') is not null drop function f_str
go

CREATE FUNCTION dbo.f_str(@id int)
RETURNS varchar(8000)
AS
BEGIN
    DECLARE @r varchar(8000)
    SET @r = ''
    SELECT @r = @r + ';' + id3
    FROM id_t
    WHERE

[email protected]
    RETURN STUFF(@r, 1, 1, '')
END
GO
-- 呼叫函式

SELECt id1, [order]=dbo.f_str(id1)
FROM id_t
GROUP BY id1

相關推薦

no