Column level vs table level constraints in sql server?

前端 未结 4 888
逝去的感伤
逝去的感伤 2021-02-07 19:43

a. Column Level

GO

CREATE TABLE Products
(
ProductID INT CONSTRAINT pk_products_pid PRIMARY KEY,
ProductName VARCHAR(25)
);

GO

b.

4条回答
  •  庸人自扰
    2021-02-07 20:02

    Your first example declares the constraint in line, the second does not. Only simple keys (involve one attribute) can be declared in line, compound keys (involving multiple columns) cannot. But both are table-level constraints!


    There are four logical levels of constraint:

    1) Column level:

    CHECK ( ProductID > 0 )
    

    2) Row level:

    CHECK ( Product_start_date < Product_end_date )
    

    3) Table level (the following example is not yet supported in SQL Server):

    CHECK ( NOT EXISTS ( SELECT *
                           FROM ( SELECT ROW_NUMBER() OVER ( PARTITION BY ProductID ) AS Tally
                                    FROM Products AS P ) AS DT1 
                          WHERE Tally > 1 ) )
    

    4) Database level (not yet supported in SQL Server):

    CREATE ASSERTION EnterpriseUniqueIds
       CHECK ( NOT EXISTS ( SELECT *
                              FROM ProductID AS P
                                   JOIN Components AS C
                                      ON C.ComponentID = P.ProductID ) );
    

    A key constraint involves comparing different rows within the same table, therefore it is a table-level constraint.

提交回复
热议问题