Как вывести внешний ключ и его ссылочный столбец в существующий SQL запрос к серверу - PullRequest
0 голосов
/ 27 марта 2020

Я использую следующий запрос для вывода списка ограничений таблицы (первичные ключи, уникальные ключи, ключи по умолчанию), однако мне трудно получить список внешних ключей и их ссылок (столбцы).

Может кто-нибудь сообщить мне, как я могу изменить этот код, чтобы я мог получить список внешних ключей и его ссылок (столбцов), сохраняя при этом PK и UQ одинаковыми.

* * Мне нужно будет использовать код для моего проекта, поэтому я был бы признателен, если бы вы могли мне, как изменить запрос.

ОБНОВЛЕНО Модифицированная версия : добавлено запрос, предложенный @ Deepak

Я заменил подзапрос внешнего ключа (после первого объединения всех) на код @ Deepak, но есть ошибка

"select table_view,
    object_type, 
    constraint_type,
    constraint_name,
    details,
    fk_columns,
    pk_columns
from (
    select schema_name(t.schema_id) + '.' + t.[name] as table_view, 
        case when t.[type] = 'U' then 'Table'
            when t.[type] = 'V' then 'View'
            end as [object_type],
        case when c.[type] = 'PK' then 'Primary key'
            when c.[type] = 'UQ' then 'Unique constraint'
            when i.[type] = 1 then 'Unique clustered index'
            when i.type = 2 then 'Unique index'
            end as constraint_type, 
        isnull(c.[name], i.[name]) as constraint_name,
        substring(column_names, 1, len(column_names)-1) as [details]
    from sys.objects t
        left outer join sys.indexes i
            on t.object_id = i.object_id
        left outer join sys.key_constraints c
            on i.object_id = c.parent_object_id 
            and i.index_id = c.unique_index_id
       cross apply (select col.[name] + ', '
                        from sys.index_columns ic
                            inner join sys.columns col
                                on ic.object_id = col.object_id
                                and ic.column_id = col.column_id
                        where ic.object_id = t.object_id
                            and ic.index_id = i.index_id
                                order by col.column_id
                                for xml path ('') ) D (column_names)
    where is_unique = 1
    and t.is_ms_shipped <> 1
    union all 
    SELECT schema_name(fk_tab.schema_id) + '.' + fk_tab.name as foreign_table,
        'Table',
        'Foreign key',
        fk.name as fk_constraint_name,
        schema_name(pk_tab.schema_id) + '.' + pk_tab.name,
        col.[name] as [fk_columns],
        col2.[name] as [pk_columns],
        schema_name(objects.schema_id) + '.' + objects.[name] + '.' + col.[name] + ' --> ' + schema_name(pk_tab.schema_id) + '.' + pk_tab.name + '.' + col2.[name] as details
    FROM
        sys.objects objects
        INNER JOIN sys.tables fk_tab on objects.object_id = fk_tab.object_id
        INNER JOIN sys.foreign_keys fk on fk_tab.object_id = fk.parent_object_id
        INNER JOIN sys.tables pk_tab on pk_tab.object_id = fk.referenced_object_id
        INNER JOIN sys.foreign_key_columns fk_c on fk_c.parent_object_id = fk.parent_object_id
                       and fk_c.constraint_object_id = fk.object_id
            inner join sys.columns col
                            on fk_c.parent_object_id = col.object_id
                            and fk_c.parent_column_id = col.column_id
        left join sys.columns col2
                            on fk_c.referenced_object_id = col2.object_id
                            and fk_c.referenced_column_id = col2.column_id
    union all
    select schema_name(t.schema_id) + '.' + t.[name],
        'Table',
        'Check constraint',
        con.[name] as constraint_name,
        con.[definition]
    from sys.check_constraints con
        left outer join sys.objects t
            on con.parent_object_id = t.object_id
        left outer join sys.all_columns col
            on con.parent_column_id = col.column_id
            and con.parent_object_id = col.object_id
    union all
    select schema_name(t.schema_id) + '.' + t.[name],
        'Table',
        'Default constraint',
        con.[name],
        col.[name] + ' = ' + con.[definition]
    from sys.default_constraints con
        left outer join sys.objects t
            on con.parent_object_id = t.object_id
        left outer join sys.all_columns col
            on con.parent_column_id = col.column_id
            and con.parent_object_id = col.object_id) a
order by table_view, constraint_type, constraint_name"

Вот ошибка сообщение:

SQLServerException: все запросы, объединенные с использованием оператора UNION, INTERSECT или EXCEPT, должны иметь одинаковое количество выражений в своих целевых списках.

Мой исходный код: см. от Источник: Dataedo's List all ограничение таблицы

"select table_view,
    object_type, 
    constraint_type,
    constraint_name,
    details
from (
    select schema_name(t.schema_id) + '.' + t.[name] as table_view, 
        case when t.[type] = 'U' then 'Table'
            when t.[type] = 'V' then 'View'
            end as [object_type],
        case when c.[type] = 'PK' then 'Primary key'
            when c.[type] = 'UQ' then 'Unique constraint'
            when i.[type] = 1 then 'Unique clustered index'
            when i.type = 2 then 'Unique index'
            end as constraint_type, 
        isnull(c.[name], i.[name]) as constraint_name,
        substring(column_names, 1, len(column_names)-1) as [details]
    from sys.objects t
        left outer join sys.indexes i
            on t.object_id = i.object_id
        left outer join sys.key_constraints c
            on i.object_id = c.parent_object_id 
            and i.index_id = c.unique_index_id
       cross apply (select col.[name] + ', '
                        from sys.index_columns ic
                            inner join sys.columns col
                                on ic.object_id = col.object_id
                                and ic.column_id = col.column_id
                        where ic.object_id = t.object_id
                            and ic.index_id = i.index_id
                                order by col.column_id
                                for xml path ('') ) D (column_names)
    where is_unique = 1
    and t.is_ms_shipped <> 1
    union all 
    select schema_name(fk_tab.schema_id) + '.' + fk_tab.name as foreign_table,
        'Table',
        'Foreign key',
        fk.name as fk_constraint_name,
        schema_name(pk_tab.schema_id) + '.' + pk_tab.name
    from sys.foreign_keys fk
        inner join sys.tables fk_tab
            on fk_tab.object_id = fk.parent_object_id
        inner join sys.tables pk_tab
            on pk_tab.object_id = fk.referenced_object_id
        inner join sys.foreign_key_columns fk_cols
            on fk_cols.constraint_object_id = fk.object_id
    union all
    select schema_name(t.schema_id) + '.' + t.[name],
        'Table',
        'Check constraint',
        con.[name] as constraint_name,
        con.[definition]
    from sys.check_constraints con
        left outer join sys.objects t
            on con.parent_object_id = t.object_id
        left outer join sys.all_columns col
            on con.parent_column_id = col.column_id
            and con.parent_object_id = col.object_id
    union all
    select schema_name(t.schema_id) + '.' + t.[name],
        'Table',
        'Default constraint',
        con.[name],
        col.[name] + ' = ' + con.[definition]
    from sys.default_constraints con
        left outer join sys.objects t
            on con.parent_object_id = t.object_id
        left outer join sys.all_columns col
            on con.parent_column_id = col.column_id
            and con.parent_object_id = col.object_id) a
where table_view like 'dbo.AREA%'
order by table_view, constraint_type, constraint_name"

Пожалуйста, дайте мне знать, если что-то неясно.

Большое спасибо

1 Ответ

1 голос
/ 27 марта 2020

Вот полный sql

select table_view,
    object_type, 
    constraint_type,
    constraint_name,
    details,
    fk_columns,
    refrenceTable,
    pk_columns
from (
    select schema_name(t.schema_id) + '.' + t.[name] as table_view, 
        case when t.[type] = 'U' then 'Table'
            when t.[type] = 'V' then 'View'
            end as [object_type],
        case when c.[type] = 'PK' then 'Primary key'
            when c.[type] = 'UQ' then 'Unique constraint'
            when i.[type] = 1 then 'Unique clustered index'
            when i.type = 2 then 'Unique index'
            end as constraint_type, 
        isnull(c.[name], i.[name]) as constraint_name,
        substring(column_names, 1, len(column_names)-1) as [details],
        '' fk_columns,
        '' refrenceTable,
        '' pk_columns
    from sys.objects t
        left outer join sys.indexes i
            on t.object_id = i.object_id
        left outer join sys.key_constraints c
            on i.object_id = c.parent_object_id 
            and i.index_id = c.unique_index_id
       cross apply (select col.[name] + ', '
                        from sys.index_columns ic
                            inner join sys.columns col
                                on ic.object_id = col.object_id
                                and ic.column_id = col.column_id
                        where ic.object_id = t.object_id
                            and ic.index_id = i.index_id
                                order by col.column_id
                                for xml path ('') ) D (column_names)
    where is_unique = 1
    and t.is_ms_shipped <> 1
    union all 
    SELECT schema_name(fk_tab.schema_id) + '.' + fk_tab.name as foreign_table,
        'Table',
        'Foreign key',
        fk.name as fk_constraint_name,
        schema_name(objects.schema_id) + '.' + objects.[name] + '.' + col.[name] + ' --> ' + schema_name(pk_tab.schema_id) + '.' + pk_tab.name + '.' + col2.[name] as details,
        col.[name] as [fk_columns],
        schema_name(pk_tab.schema_id) + '.' + pk_tab.name,
        col2.[name] as [pk_columns]
    FROM
        sys.objects objects
        INNER JOIN sys.tables fk_tab on objects.object_id = fk_tab.object_id
        INNER JOIN sys.foreign_keys fk on fk_tab.object_id = fk.parent_object_id
        INNER JOIN sys.tables pk_tab on pk_tab.object_id = fk.referenced_object_id
        INNER JOIN sys.foreign_key_columns fk_c on fk_c.parent_object_id = fk.parent_object_id
                       and fk_c.constraint_object_id = fk.object_id
            inner join sys.columns col
                            on fk_c.parent_object_id = col.object_id
                            and fk_c.parent_column_id = col.column_id
        left join sys.columns col2
                            on fk_c.referenced_object_id = col2.object_id
                            and fk_c.referenced_column_id = col2.column_id
    union all
    select schema_name(t.schema_id) + '.' + t.[name],
        'Table',
        'Check constraint',
        con.[name] as constraint_name,
        con.[definition],
         '' as [fk_columns],
        '' refrenceTable,
        '' as [pk_columns]
    from sys.check_constraints con
        left outer join sys.objects t
            on con.parent_object_id = t.object_id
        left outer join sys.all_columns col
            on con.parent_column_id = col.column_id
            and con.parent_object_id = col.object_id
    union all
    select schema_name(t.schema_id) + '.' + t.[name],
        'Table',
        'Default constraint',
        con.[name],
        col.[name] + ' = ' + con.[definition],
         '' as [fk_columns],
        '' refrenceTable,
        '' as [pk_columns]
    from sys.default_constraints con
        left outer join sys.objects t
            on con.parent_object_id = t.object_id
        left outer join sys.all_columns col
            on con.parent_column_id = col.column_id
            and con.parent_object_id = col.object_id) a
order by table_view, constraint_type, constraint_name
...