sql >> Database >  >> RDS >> Sqlserver

één kolom aaneenschakelen in TSQL

U kunt FOR XML PATH('') . gebruiken zoals dit:

DECLARE @TestData TABLE
(
     address_desc NVARCHAR(100) NOT NULL
    ,people_id UNIQUEIDENTIFIER NOT NULL
);

INSERT  @TestData 
SELECT  'Murfreesboro, TN  37130',              'F15D1135-9947-4F66-B778-00E43EC44B9E'
UNION ALL
SELECT  '11 Mohawk Rd., Burlington, MA 01803',  'C561918F-C2E9-4507-BD7C-00FB688D2D6E'
UNION ALL
SELECT  'Unknown, UN  00000',                   'C561918F-C2E9-4507-BD7C-00FB688D2D6E'
UNION ALL
SELECT  'Memphis, TN  38133',                   '8ED8C601-5D35-4EB7-9217-012905D6E9F1'
UNION ALL
SELECT  '44 Maverick St., Fitchburg, MA',       '8ED8C601-5D35-4EB7-9217-012905D6E9F1';

SELECT  a.people_id,
    (SELECT SUBSTRING(
        (SELECT ';'+b.address_desc
        FROM    @TestData b 
        WHERE   a.people_id = b.people_id
        FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')
        ,2
        ,4000)
    ) GROUP_CONCATENATE
FROM    @TestData a
GROUP BY a.people_id

Resultaten:

people_id                            GROUP_CONCATENATE
------------------------------------ ------------------------------------------------------
F15D1135-9947-4F66-B778-00E43EC44B9E Murfreesboro, TN  37130
C561918F-C2E9-4507-BD7C-00FB688D2D6E 11 Mohawk Rd., Burlington, MA 01803;Unknown, UN  00000
8ED8C601-5D35-4EB7-9217-012905D6E9F1 Memphis, TN  38133;44 Maverick St., Fitchburg, MA



  1. Is er een manier om automatisch een UML-diagram te genereren?

  2. Auto-increment emuleren in MySQL/InnoDB

  3. Hoe fouten in sqlplus weer te geven

  4. SQL Server 2005 en tijdelijk tabelbereik