Как получить первичный ключ или подробности ключевого ограничения для столбцов из Information_Schema.Columns? - PullRequest
1 голос
/ 08 июля 2019

Как получить первичный ключ или подробности ограничения ключа для столбцов из Information_Schema.Columns?

Я получаю вывод из sys.indexes, однако при соединении запроса с Information_Schema я получаю повторяющиеся записи ..

SELECT      COLUMN_NAME AS COLUMNNAME,  
            DATA_TYPE AS DATATYPE,
            CHARACTER_MAXIMUM_LENGTH,
            IS_NULLABLE
            -- Expected -- Another Column --- Which has  Index Details -- Whether Primary Key or Foreign Key or No Key
FROM        INFORMATION_SCHEMA.COLUMNS  
WHERE       TABLE_NAME = 'MyTable'



SELECT 
     TableName = t.name,
     IndexName = ind.name,
     ColumnName = col.name
FROM 
     sys.indexes ind 
INNER JOIN 
     sys.index_columns ic ON  ind.object_id = ic.object_id and ind.index_id = ic.index_id 
INNER JOIN 
     sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id 
INNER JOIN 
     sys.tables t ON ind.object_id = t.object_id 

WHERE t.name = 'MyTable'

Ответы [ 2 ]

1 голос
/ 08 июля 2019

Это может помочь

USE AdventureWorks2014
GO
;WITH DetailInfo
AS(
SELECT 
    o.name TableName,
    c.name ColumnName,
    t.Name DataType,
    c.max_length MaxLength,
    c.precision Precision,
    c.scale Scale,
    c.is_nullable IsNull,
    ISNULL(i.is_primary_key, 0) 'PrimaryKey',
    ISNULL(i.is_unique_constraint, 0) 'UniqueKey',
    ISNULL(i.name, 0) 'IndexName',
    ISNULL(i.type_desc, 0) 'IndexType',
    ISNULL(i.is_disabled, 0) 'IndexDisabled'
FROM  sys.objects o
INNER JOIN sys.columns c ON o.object_id = c.object_id
INNER JOIN sys.types t ON c.user_type_id = t.user_type_id
LEFT OUTER JOIN sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
LEFT OUTER JOIN sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
)
SELECT * FROM DetailInfo
WHERE TableName = 'Employee'

enter image description here

/ --------- ИЛИ --------------------- /

USE AdventureWorks2014
GO
;WITH ContraintDetails 
AS(
--KEY_CONSTRAINT
SELECT schema_name(o.schema_id) + '.' + o.[name] TableName,   
        c.name as ColumnName,
        k.type_desc ConstantType,
        k.[name] ConstantName,
        'Is Enforced :' + CASE WHEN  k.is_enforced = 1 THEN 'YES' ELSE 'NO' END Details 
FROM sys.key_constraints  k
INNER JOIN sys.all_columns a ON k.parent_object_id = a.object_id
INNER JOIN sys.columns c ON a.object_id = c.object_id AND a.column_id = c.column_id
INNER JOIN sys.objects o ON  c.object_id = o.object_id

UNION ALL
--DEFAULT_CONSTRAINT
SELECT schema_name(t.schema_id) + '.' + t.[name] TableName,   
        c.name as ColumnName,
        con.type_desc ConstantType,
        con.[name] ConstantName,
        col.[name] + ' : ' + con.[definition] Details
FROM sys.default_constraints con
INNER JOIN sys.objects t on con.parent_object_id = t.object_id
INNER JOIN sys.all_columns col on con.parent_column_id = col.column_id and con.parent_object_id = col.object_id
INNER JOIN sys.columns c ON col.object_id = c.object_id AND col.column_id = c.column_id

UNION ALL

-- FOREIGN_KEY_CONSTRAINT
SELECT schema_name(fk_tab.schema_id) + '.' + fk_tab.name as TableName,
c.name as ColumnName,
fk.type_desc ConstraintType,
fk.name as ConstraintName,
schema_name(pk_tab.schema_id) + '.' + pk_tab.name Details
from sys.foreign_keys fk
INNER JOIN sys.objects o ON fk.parent_object_id = o.object_id
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
INNER JOIN sys.columns c ON fk_cols.parent_object_id = c.object_id AND fk_cols.parent_column_id = c.column_id

UNION ALL

--CHECK_CONSTRAINT
SELECT schema_name(t.schema_id) + '.' + t.[name] TableName,
c.name as ColumnName,
con.type_desc  ConstraintType,
con.[name] as constraint_name,
con.[definition] Details
FROM sys.check_constraints con
INNER JOIN sys.objects t on con.parent_object_id = t.object_id
INNER JOIN sys.all_columns col on con.parent_column_id = col.column_id and con.parent_object_id = col.object_id
INNER JOIN sys.columns c ON col.object_id = c.object_id AND col.column_id = c.column_id

UNION ALL
-- INDEX
SELECT schema_name(o.schema_id) + '.' + o.[name] TableName,
    c.name as ColumnName,
    i.type_desc ConstantType,
    i.[name] ConstantName,
    'Is Disabled :' + CASE WHEN  i.is_disabled = 1 THEN 'YES' ELSE 'NO' END Details
FROM sys.indexes  i
INNER JOIN sys.index_columns ic ON  i.object_id = ic.object_id
INNER JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
INNER JOIN sys.objects o ON  c.object_id = o.object_id
)
SELECT * FROM ContraintDetails
WHERE TableName = 'HumanResources.Employee' AND  ColumnName = 'BirthDate'

ORDER BY TableName,ColumnName

enter image description here

0 голосов
/ 08 июля 2019

Ваш вопрос немного неясен, но я думаю, что вы можете получить, где вы хотите, используя следующие запросы. Первый выводит все ограничения и столбцы в них. Второй выводит все столбцы и, если они являются частью ограничений, дополнительную информацию. В частности, я думаю, что INFORMATION_SCHEMA.TABLE_CONSTRAINTS.CONSTRAINT_TYPE - это нужный вам столбец.

-- Constraint columns.
select KCU.TABLE_CATALOG, KCU.TABLE_SCHEMA, KCU.TABLE_NAME, TC.CONSTRAINT_NAME, KCU.COLUMN_NAME, KCU.ORDINAL_POSITION, TC.CONSTRAINT_TYPE
  from INFORMATION_SCHEMA.TABLE_CONSTRAINTS as TC inner join
    INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE as CCU on
      CCU.CONSTRAINT_CATALOG = TC.CONSTRAINT_CATALOG and CCU.CONSTRAINT_SCHEMA = TC.CONSTRAINT_SCHEMA and CCU.CONSTRAINT_NAME = TC.CONSTRAINT_NAME inner join
    INFORMATION_SCHEMA.KEY_COLUMN_USAGE as KCU on
      KCU.CONSTRAINT_CATALOG = CCU.CONSTRAINT_CATALOG and KCU.CONSTRAINT_SCHEMA = CCU.CONSTRAINT_SCHEMA and KCU.CONSTRAINT_NAME = CCU.CONSTRAINT_NAME and KCU.COLUMN_NAME = CCU.COLUMN_NAME
  order by KCU.TABLE_CATALOG, KCU.TABLE_SCHEMA, KCU.TABLE_NAME, TC.CONSTRAINT_NAME, KCU.ORDINAL_POSITION, KCU.COLUMN_NAME;

-- All columns.
select C.TABLE_CATALOG, C.TABLE_SCHEMA, C.TABLE_NAME, S.CONSTRAINT_NAME, C.COLUMN_NAME, S.ORDINAL_POSITION, S.CONSTRAINT_TYPE
  from INFORMATION_SCHEMA.COLUMNS as C left outer join
    ( select KCU.TABLE_CATALOG, KCU.TABLE_SCHEMA, KCU.TABLE_NAME, TC.CONSTRAINT_NAME, KCU.COLUMN_NAME, KCU.ORDINAL_POSITION, TC.CONSTRAINT_TYPE
        from INFORMATION_SCHEMA.TABLE_CONSTRAINTS as TC inner join
          INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE as CCU on
            CCU.CONSTRAINT_CATALOG = TC.CONSTRAINT_CATALOG and CCU.CONSTRAINT_SCHEMA = TC.CONSTRAINT_SCHEMA and CCU.CONSTRAINT_NAME = TC.CONSTRAINT_NAME inner join
          INFORMATION_SCHEMA.KEY_COLUMN_USAGE as KCU on
            KCU.CONSTRAINT_CATALOG = CCU.CONSTRAINT_CATALOG and KCU.CONSTRAINT_SCHEMA = CCU.CONSTRAINT_SCHEMA and KCU.CONSTRAINT_NAME = CCU.CONSTRAINT_NAME and KCU.COLUMN_NAME = CCU.COLUMN_NAME
       ) as S on
         S.TABLE_CATALOG = C.TABLE_CATALOG and S.TABLE_SCHEMA = C.TABLE_SCHEMA and S.TABLE_NAME = C.TABLE_NAME and S.COLUMN_NAME = C.COLUMN_NAME
  order by C.TABLE_CATALOG, C.TABLE_SCHEMA, C.TABLE_NAME, S.CONSTRAINT_NAME, S.ORDINAL_POSITION, C.COLUMN_NAME;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...