Wednesday, 19 December 2012
Concatenate all the rows values into single row :
Script to create a table and load the data :
CREATE TABLE test_rowconcatenate
(
id INT IDENTITY(1, 1),
name VARCHAR(10)
)
SELECT *
FROM test_rowconcatenate
INSERT INTO test_rowconcatenate
VALUES ('A'),
('B'),
('C'),
('D'),
('E'),
('F'),
('G'),
('H'),
('I'),
('J'),
('K'),
('L'),
('M'),
('N'),
('O'),
('P')
SELECT *
FROM test_rowconcatenate
Ways to concatenate all the row values into single record :
1).
DECLARE @string VARCHAR(max) = ''
SELECT @string = @string + ',' + name
FROM test_rowconcatenate
PRINT Substring(@string, 2, Len(@string))
2).
DECLARE @string VARCHAR(max)='',
@field VARCHAR(10)='',
@i INT = 1,
@n INT
SELECT @n = Count(0)
FROM test_rowconcatenate
WHILE( @i <= @n )
BEGIN
SELECT @field = name
FROM (SELECT name,
Row_number()
OVER(
ORDER BY id) row_id
FROM test_rowconcatenate) a
WHERE row_id = @i
SET @string = @string + ',' + @field
SET @i = @i + 1
END
PRINT Substring(@string, 2, Len(@string))
3).
DECLARE @string VARCHAR(max) ='',
@field VARCHAR(10)
DECLARE test_cur CURSOR FOR
SELECT name
FROM test_rowconcatenate
OPEN test_cur
FETCH FROM test_cur INTO @field
WHILE @@Fetch_status = 0
BEGIN
SET @string = @string + ',' + @field
FETCH FROM test_cur INTO @field
END
CLOSE test_cur
DEALLOCATE test_cur
PRINT Stuff(@string, 1, 1, '')
4).
SELECT Stuff((SELECT ',' + name
FROM test_rowconcatenate
FOR xml path('')), 1, 1, '')
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment