有没有办法可以创建一个约束来检查SQL Server中两列的值?

时间:2014-10-05 10:08:00

标签: sql-server

我有这个DDL:

CREATE TABLE [dbo].[AdminTest] (
    [AdminTestId]  INT            IDENTITY (1, 1) NOT NULL,
    [Title]        NVARCHAR (100) NOT NULL,
    [CreatedBy]    INT            NOT NULL,
    [CreatedDate]  DATETIME       NOT NULL,
    [ModifiedBy]   INT            NOT NULL,
    [ModifiedDate] DATETIME       NOT NULL,
    [TestLevelId]  INT            NOT NULL,
    [TestStatusId] INT            NOT NULL,
    [ExamId]       INT            NOT NULL,
    [Text]         NVARCHAR (MAX) NULL,
    [Sequence]     INT            DEFAULT ((1)) NOT NULL,
    [Release]      NVARCHAR (50)  DEFAULT ((1)) NOT NULL,
    [Version]      ROWVERSION     NOT NULL,
    [Price]        MONEY          DEFAULT ((0)) NOT NULL,
    [ReleaseDate]  DATETIME       NULL,
    [Code]         VARCHAR (10)   DEFAULT (LEFT(newid(), (5))) NOT NULL
);

如果ReleaseDate列的值为2,我是否可以要求Release设置值?

3 个答案:

答案 0 :(得分:3)

是:

alter table dbo.AdminTest
add constraint CK_AdminTest_VerifyReleaseAndDate CHECK (Release = N'2' AND ReleaseDate IS NOT NULL OR Release <> N'2');

答案 1 :(得分:0)

虽然ALTER:

ALTER TABLE AdminTest

ADD CONSTRAINT DF_Check CHECK (Release=2)  ;

创造时

CREATE TABLE ADMIN(
Release int
  CONSTRAINT DF_Check CHECK (Release=2) 
 )

答案 2 :(得分:0)

您还可以将检查约束内联定义为列约束,如下所示 -

CREATE TABLE [dbo].[AdminTest] (
    [AdminTestId]  INT            IDENTITY (1, 1) NOT NULL,
    [Release]      NVARCHAR (50)  DEFAULT ((1)) NOT NULL,
    [ReleaseDate]  DATETIME  NULL CONSTRAINT CK_Release CHECK (Release='2') ,
    [Code]         VARCHAR (10)   DEFAULT (LEFT(newid(), (5))) NOT NULL
);