3

With this query I get the list of all my database's CHECK, FOREIGN_KEY, PRIMARY_KEY and UNIQUE_KEY constraints.

SELECT 
    o.object_id as ID, o.name AS Name, 
    OBJECT_NAME(o.parent_object_id) AS TableName, 
    o.type_desc AS TypeName, 
    cs.COLUMN_NAME as ColumnName
FROM 
    sys.objects o 
LEFT JOIN 
    INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE cs ON o.name = cs.CONSTRAINT_NAME 
WHERE 
    o.type = 'C' or o.type = 'F' or o.type = 'PK' or o.type = 'UQ'

However, there are some of them with many 'ColumnName' and I want to concat this.

For example :

  'PK_ENTITE_SIGN_DOSSIER_ID_DOSSIER_ID_ENTITE_ID_GROUPE_SIGN_ID_PERSONNE_ID_SCHEMA'

is a PRIMARY_KEY on table ENTITE_SIGN_DOSSIER and contains ID_DOSSIER, ID_ENTITE, ID_GROUPE_SIGN, ID_PERSONNE and ID_SCHEMA (5 columns) and in this case, my query return 5 lines for this constraint.

How can I concat those columns name on the query's result please ?

Thanks a lot for your help

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
J.P.A
  • 95
  • 6
  • 2
    A simple search in your favorite search engine on "stackoverflow sql server concatenate row values" will yield many examples on how to concatenate the column names. First two examples I found should shed some light on this: [1](https://stackoverflow.com/questions/1874966/concatenate-row-values-t-sql) and [2](https://stackoverflow.com/questions/5196371/sql-query-concatenating-results-into-one-string). – TT. Jul 10 '15 at 08:04

1 Answers1

3

This is standard xml and stuff function trick:

SELECT  o.object_id AS ID ,
        o.name AS Name ,
        OBJECT_NAME(o.parent_object_id) AS TableName ,
        o.type_desc AS TypeName ,
        ca.ColumnName
FROM    sys.objects o
        CROSS APPLY ( SELECT    STUFF(( SELECT  ', ' + cs.COLUMN_NAME
                                        FROM    INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE cs
                                        WHERE   o.name = cs.CONSTRAINT_NAME
                                      FOR
                                        XML PATH('')
                                      ), 1, 2, '') AS ColumnName
                    ) ca
WHERE   o.type = 'C'
        OR o.type = 'F'
        OR o.type = 'PK'
        OR o.type = 'UQ'
ORDER BY ID   
Giorgi Nakeuri
  • 35,155
  • 8
  • 47
  • 75