Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL Server获取约束列信息_Sql_Sql Server_Database - Fatal编程技术网

SQL Server获取约束列信息

SQL Server获取约束列信息,sql,sql-server,database,Sql,Sql Server,Database,我想为SQL Server编写一个DB查询,以获取以下列信息: 我有它的列名 列描述我有它 数据类型我有它 约束为主键、外键、为空、检查约束、默认约束、唯一 我有吗 我当前的查询是,我希望在单独的列中包含检查约束和默认约束: SELECT c.name AS 'name', t.name AS 'dataType', t.name + '(' + CAST(c.max_length AS varchar(50)) +')' AS 'fullType', ISNULL(

我想为SQL Server编写一个DB查询,以获取以下列信息:

我有它的列名 列描述我有它 数据类型我有它 约束为主键、外键、为空、检查约束、默认约束、唯一 我有吗 我当前的查询是,我希望在单独的列中包含检查约束和默认约束:

SELECT 
    c.name AS 'name', t.name AS 'dataType',
    t.name + '(' + CAST(c.max_length AS varchar(50)) +')' AS 'fullType', 
    ISNULL(sep.value,'') [Description],
    CASE
       WHEN c.is_nullable = 1 THEN 'null' ELSE 'not null'
    END AS 'Constraint',
    CASE 
       WHEN fk.object_id IS NOT NULL THEN 'foreign key' ELSE NULL 
    END AS relation,
    schema_name(pk_tab.schema_id) + '.' + pk_tab.name AS referenceTable,
    ISNULL(i.is_primary_key, 0) AS 'isprimarykey',
    i.name as 'index'
FROM
    sys.tables tab
INNER JOIN 
    sys.columns c ON c.object_id = tab.object_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
LEFT OUTER JOIN 
    sys.foreign_key_columns fk_cols ON fk_cols.parent_object_id = tab.object_id
                                    AND fk_cols.parent_column_id = c.column_id
LEFT OUTER JOIN 
    sys.foreign_keys fk ON fk.object_id = fk_cols.constraint_object_id
LEFT OUTER JOIN 
    sys.tables pk_tab ON pk_tab.object_id = fk_cols.referenced_object_id
LEFT OUTER JOIN 
    sys.columns pk_col ON pk_col.column_id = fk_cols.referenced_column_id
                       AND pk_col.object_id = fk_cols.referenced_object_id
LEFT JOIN 
    sys.extended_properties sep ON c.object_id = sep.major_id 
                                AND c.column_id = sep.minor_id 
                                AND sep.name = 'MS_Description'
JOIN 
    sys.types t ON c.user_type_id = t.user_type_id
WHERE 
    c.object_id = Object_id('sometableName')

为了克服这个问题,我们需要使用sys.check\u约束和sys.default\u约束。首先,我们需要创建一个内联表值函数,因为一列可以包含多个约束。以下查询将创建一个表值参数,并返回默认值和检查约束详细信息

CREATE FUNCTION  ContraintView
( @ColId AS INT , @ColIndexId AS INT)
RETURNS TABLE
AS
RETURN

SELECT * FROM (

   select schema_name(t.schema_id) + '.' + t.[name] AS ConstraintName,

        'Check constraint' AS constraint_type,
        con.[name] as constraint_name,
        con.[definition] ,

 col.object_id,
  col.column_id 

    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],

        'Default constraint',
        con.[name],
        col.[name] + ' = ' + con.[definition] ,
         col.object_id ,
         col.column_id 
    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
    ) AS TMP_TBL
    WHERE TMP_TBL.object_id =@ColId  AND TMP_TBL.column_id = @ColIndexId
然后,我们将此函数应用于您的查询

SELECT * FROM (
SELECT 
    c.name AS 'name', t.name AS 'dataType',
    t.name + '(' + CAST(c.max_length AS varchar(50)) +')' AS 'fullType', 
    ISNULL(sep.value,'') [Description],
    CASE
       WHEN c.is_nullable = 1 THEN 'null' ELSE 'not null'
    END AS 'Constraint',
    CASE 
       WHEN fk.object_id IS NOT NULL THEN 'foreign key' ELSE NULL 
    END AS relation,
    schema_name(pk_tab.schema_id) + '.' + pk_tab.name AS referenceTable,
    ISNULL(i.is_primary_key, 0) AS 'isprimarykey',
    i.name as 'index',
    c.object_id ,
    c.column_id
FROM
    sys.tables tab
INNER JOIN 
    sys.columns c ON c.object_id = tab.object_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
LEFT OUTER JOIN 
    sys.foreign_key_columns fk_cols ON fk_cols.parent_object_id = tab.object_id
                                    AND fk_cols.parent_column_id = c.column_id
LEFT OUTER JOIN 
    sys.foreign_keys fk ON fk.object_id = fk_cols.constraint_object_id
LEFT OUTER JOIN 
    sys.tables pk_tab ON pk_tab.object_id = fk_cols.referenced_object_id
LEFT OUTER JOIN 
    sys.columns pk_col ON pk_col.column_id = fk_cols.referenced_column_id
                       AND pk_col.object_id = fk_cols.referenced_object_id
LEFT JOIN 
    sys.extended_properties sep ON c.object_id = sep.major_id 
                                AND c.column_id = sep.minor_id 
                                AND sep.name = 'MS_Description'
JOIN 
    sys.types t ON c.user_type_id = t.user_type_id

WHERE 
    c.object_id = Object_id('HumanResources.Employee')

    ) AS TMP_TBL OUTER APPLY  dbo.ContraintView( TMP_TBL.object_id ,TMP_TBL.column_id)
输出将类似于

+-------------------+------------------+----------------------+-------------------------------------------------------------------------------------------------------------------------+------------+-------------+----------------+--------------+------------------------------------------------+-----------+-----------+-------------------------+--------------------+----------------------------+----------------------------------------------------------------------------+-----------+-----------+
|       name        |     dataType     |       fullType       |                                                       Description                                                       | Constraint |  relation   | referenceTable | isprimarykey |                     index                      | object_id | column_id |     ConstraintName      |  constraint_type   |      constraint_name       |                                 definition                                 | object_id | column_id |
+-------------------+------------------+----------------------+-------------------------------------------------------------------------------------------------------------------------+------------+-------------+----------------+--------------+------------------------------------------------+-----------+-----------+-------------------------+--------------------+----------------------------+----------------------------------------------------------------------------+-----------+-----------+
| BusinessEntityID  | int              | int(4)               | Primary key for Employee records.  Foreign key to BusinessEntity.BusinessEntityID.                                      | not null   | foreign key | Person.Person  |            1 | PK_Employee_BusinessEntityID                   | 981578535 |         1 | NULL                    | NULL               | NULL                       | NULL                                                                       | NULL      | NULL      |
| NationalIDNumber  | nvarchar         | nvarchar(30)         | Unique national identification number such as a social security number.                                                 | not null   | NULL        | NULL           |            0 | AK_Employee_NationalIDNumber                   | 981578535 |         2 | NULL                    | NULL               | NULL                       | NULL                                                                       | NULL      | NULL      |
| LoginID           | nvarchar         | nvarchar(512)        | Network login.                                                                                                          | not null   | NULL        | NULL           |            0 | AK_Employee_LoginID                            | 981578535 |         3 | NULL                    | NULL               | NULL                       | NULL                                                                       | NULL      | NULL      |
| OrganizationNode  | hierarchyid      | hierarchyid(892)     | Where the employee is located in corporate hierarchy.                                                                   | null       | NULL        | NULL           |            0 | IX_Employee_OrganizationNode                   | 981578535 |         4 | NULL                    | NULL               | NULL                       | NULL                                                                       | NULL      | NULL      |
| OrganizationNode  | hierarchyid      | hierarchyid(892)     | Where the employee is located in corporate hierarchy.                                                                   | null       | NULL        | NULL           |            0 | IX_Employee_OrganizationLevel_OrganizationNode | 981578535 |         4 | NULL                    | NULL               | NULL                       | NULL                                                                       | NULL      | NULL      |
| OrganizationLevel | smallint         | smallint(2)          | The depth of the employee in the corporate hierarchy.                                                                   | null       | NULL        | NULL           |            0 | IX_Employee_OrganizationLevel_OrganizationNode | 981578535 |         5 | NULL                    | NULL               | NULL                       | NULL                                                                       | NULL      | NULL      |
| JobTitle          | nvarchar         | nvarchar(100)        | Work title such as Buyer or Sales Representative.                                                                       | not null   | NULL        | NULL           |            0 | NULL                                           | 981578535 |         6 | NULL                    | NULL               | NULL                       | NULL                                                                       | NULL      | NULL      |
| BirthDate         | date             | date(3)              | Date of birth.                                                                                                          | not null   | NULL        | NULL           |            0 | NULL                                           | 981578535 |         7 | HumanResources.Employee | Check constraint   | CK_Employee_BirthDate      | ([BirthDate]>='1930-01-01' AND [BirthDate]<=dateadd(year,(-18),getdate())) | 981578535 | 7         |
| MaritalStatus     | nchar            | nchar(2)             | M = Married, S = Single                                                                                                 | not null   | NULL        | NULL           |            0 | NULL                                           | 981578535 |         8 | HumanResources.Employee | Check constraint   | CK_Employee_MaritalStatus  | (upper([MaritalStatus])='S' OR upper([MaritalStatus])='M')                 | 981578535 | 8         |
| Gender            | nchar            | nchar(2)             | M = Male, F = Female                                                                                                    | not null   | NULL        | NULL           |            0 | NULL                                           | 981578535 |         9 | HumanResources.Employee | Check constraint   | CK_Employee_Gender         | (upper([Gender])='F' OR upper([Gender])='M')                               | 981578535 | 9         |
| HireDate          | date             | date(3)              | Employee hired on this date.                                                                                            | not null   | NULL        | NULL           |            0 | NULL                                           | 981578535 |        10 | HumanResources.Employee | Check constraint   | CK_Employee_HireDate       | ([HireDate]>='1996-07-01' AND [HireDate]<=dateadd(day,(1),getdate()))      | 981578535 | 10        |
| SalariedFlag      | Flag             | Flag(1)              | Job classification. 0 = Hourly, not exempt from collective bargaining. 1 = Salaried, exempt from collective bargaining. | not null   | NULL        | NULL           |            0 | NULL                                           | 981578535 |        11 | HumanResources.Employee | Default constraint | DF_Employee_SalariedFlag   | SalariedFlag = ((1))                                                       | 981578535 | 11        |
| VacationHours     | smallint         | smallint(2)          | Number of available vacation hours.                                                                                     | not null   | NULL        | NULL           |            0 | NULL                                           | 981578535 |        12 | HumanResources.Employee | Check constraint   | CK_Employee_VacationHours  | ([VacationHours]>=(-40) AND [VacationHours]<=(240))                        | 981578535 | 12        |
| VacationHours     | smallint         | smallint(2)          | Number of available vacation hours.                                                                                     | not null   | NULL        | NULL           |            0 | NULL                                           | 981578535 |        12 | HumanResources.Employee | Default constraint | DF_Employee_VacationHours  | VacationHours = ((0))                                                      | 981578535 | 12        |
| SickLeaveHours    | smallint         | smallint(2)          | Number of available sick leave hours.                                                                                   | not null   | NULL        | NULL           |            0 | NULL                                           | 981578535 |        13 | HumanResources.Employee | Check constraint   | CK_Employee_SickLeaveHours | ([SickLeaveHours]>=(0) AND [SickLeaveHours]<=(120))                        | 981578535 | 13        |
| SickLeaveHours    | smallint         | smallint(2)          | Number of available sick leave hours.                                                                                   | not null   | NULL        | NULL           |            0 | NULL                                           | 981578535 |        13 | HumanResources.Employee | Default constraint | DF_Employee_SickLeaveHours | SickLeaveHours = ((0))                                                     | 981578535 | 13        |
| CurrentFlag       | Flag             | Flag(1)              | 0 = Inactive, 1 = Active                                                                                                | not null   | NULL        | NULL           |            0 | NULL                                           | 981578535 |        14 | HumanResources.Employee | Default constraint | DF_Employee_CurrentFlag    | CurrentFlag = ((1))                                                        | 981578535 | 14        |
| rowguid           | uniqueidentifier | uniqueidentifier(16) | ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.                          | not null   | NULL        | NULL           |            0 | AK_Employee_rowguid                            | 981578535 |        15 | HumanResources.Employee | Default constraint | DF_Employee_rowguid        | rowguid = (newid())                                                        | 981578535 | 15        |
| ModifiedDate      | datetime         | datetime(8)          | Date and time the record was last updated.                                                                              | not null   | NULL        | NULL           |            0 | NULL                                           | 981578535 |        16 | HumanResources.Employee | Default constraint | DF_Employee_ModifiedDate   | ModifiedDate = (getdate())                                                 | 981578535 | 16        |
| BusinessEntityID  | int              | int(4)               | Clustered index created by a primary key constraint.                                                                    | not null   | foreign key | Person.Person  |            1 | PK_Employee_BusinessEntityID                   | 981578535 |         1 | NULL                    | NULL               | NULL                       | NULL                                                                       | NULL      | NULL      |
| NationalIDNumber  | nvarchar         | nvarchar(30)         | Unique nonclustered index.                                                                                              | not null   | NULL        | NULL           |            0 | AK_Employee_NationalIDNumber                   | 981578535 |         2 | NULL                    | NULL               | NULL                       | NULL                                                                       | NULL      | NULL      |
| LoginID           | nvarchar         | nvarchar(512)        | Unique nonclustered index.                                                                                              | not null   | NULL        | NULL           |            0 | AK_Employee_LoginID                            | 981578535 |         3 | NULL                    | NULL               | NULL                       | NULL                                                                       | NULL      | NULL      |
| OrganizationLevel | smallint         | smallint(2)          | Unique nonclustered index.                                                                                              | null       | NULL        | NULL           |            0 | IX_Employee_OrganizationLevel_OrganizationNode | 981578535 |         5 | NULL                    | NULL               | NULL                       | NULL                                                                       | NULL      | NULL      |
| JobTitle          | nvarchar         | nvarchar(100)        | Unique nonclustered index.                                                                                              | not null   | NULL        | NULL           |            0 | NULL                                           | 981578535 |         6 | NULL                    | NULL               | NULL                       | NULL                                                                       | NULL      | NULL      |
| BirthDate         | date             | date(3)              | Unique nonclustered index. Used to support replication samples.                                                         | not null   | NULL        | NULL           |            0 | NULL                                           | 981578535 |         7 | HumanResources.Employee | Check constraint   | CK_Employee_BirthDate      | ([BirthDate]>='1930-01-01' AND [BirthDate]<=dateadd(year,(-18),getdate())) | 981578535 | 7         |
+-------------------+------------------+----------------------+-------------------------------------------------------------------------------------------------------------------------+------------+-------------+----------------+--------------+------------------------------------------------+-----------+-----------+-------------------------+--------------------+----------------------------+----------------------------------------------------------------------------+-----------+-----------+

还有其他解决办法吗。此查询似乎有点慢。数据库需要多长时间?SQL Server解析和编译时间:CPU时间=94毫秒,运行时间=99毫秒。16行影响SQL Server执行时间:CPU时间=0毫秒,运行时间=3毫秒。SQL Server解析和编译时间:CPU时间=0毫秒,经过的时间=0毫秒。这些值慢吗?是的,因为我需要用脚本运行100多次以上