2000多变一
CREATE TABLE tb ( id INT, value VARCHAR(10) )
INSERT INTO tb
VALUES ( 1, 'aa' )
INSERT INTO tb
VALUES ( 1, 'bb' )
INSERT INTO tb
VALUES ( 2, 'aaa' )
INSERT INTO tb
VALUES ( 2, 'bbb' )
INSERT INTO tb
VALUES ( 2, 'ccc' )
go
CREATE FUNCTION dbo.f_str ( @id INT )
RETURNS VARCHAR(100)
AS
BEGIN
DECLARE @str VARCHAR(1000)
SET @str = ''
SELECT @str = @str + ',' + CAST(value AS VARCHAR)
FROM tb
WHERE id = @id
SET @str = RIGHT(@str, LEN(@str) - 1)
RETURN @str
END
go
--调用函数
SELECT id ,
value = dbo.f_str(id)
FROM tb
GROUP BY id
DROP FUNCTION dbo.f_str
DROP TABLE tb
INSERT INTO tb
VALUES ( 1, 'aa' )
INSERT INTO tb
VALUES ( 1, 'bb' )
INSERT INTO tb
VALUES ( 2, 'aaa' )
INSERT INTO tb
VALUES ( 2, 'bbb' )
INSERT INTO tb
VALUES ( 2, 'ccc' )
go
CREATE FUNCTION dbo.f_str ( @id INT )
RETURNS VARCHAR(100)
AS
BEGIN
DECLARE @str VARCHAR(1000)
SET @str = ''
SELECT @str = @str + ',' + CAST(value AS VARCHAR)
FROM tb
WHERE id = @id
SET @str = RIGHT(@str, LEN(@str) - 1)
RETURN @str
END
go
--调用函数
SELECT id ,
value = dbo.f_str(id)
FROM tb
GROUP BY id
DROP FUNCTION dbo.f_str
DROP TABLE tb