SQL Server TSQL: NOCHECK Foreign Key inside CREATE TABLE

cvxl0en2  于 2023-03-17  发布在  其他
关注(0)|答案(1)|浏览(160)

I want to add a foreign key constraint inline with my CREATE TABLE statement. However, I also want to include the NOCHECK attribute. Can this be done in one pass inside the CREATE TABLE statement? I can't seem to find a good example.

So, something like:

CREATE TABLE dbo.SampleTable (
   [ID] INT IDENTITY (1,1) NOT NULL,
   [ParentSampleTableID] INT NOT NULL,
   <NOCHECK> CONSTRAINT [FK_SampleTable_ParentSampleTable] FOREIGN KEY (ParentSampleTableID) REFERENCES dbo.ParentSampleTable ([ID])
)

Any ideas?

6tdlim6h

6tdlim6h1#

You cannot add a constraint and disable at table definition level.

You have two options

(1) do not add a constraint at the table definition level and later add the constraint and also disable it using NOCHECK .

CREATE TABLE dbo.SampleTable 
(
    [ID] INT IDENTITY (1,1) NOT NULL,
    [ParentSampleTableID] INT NOT NULL
)
GO   

ALTER TABLE dbo.SampleTable WITH NOCHECK 
    ADD CONSTRAINT [FK_SampleTable_ParentSampleTable] 
        FOREIGN KEY (ParentSampleTableID) REFERENCES dbo.ParentSampleTable ([ID])
GO

(2) Add constraint at table definition level and later disable it:

CREATE TABLE dbo.SampleTable 
(
    [ID] INT IDENTITY (1,1) NOT NULL,
    [ParentSampleTableID] INT NOT NULL,
    CONSTRAINT [FK_SampleTable_ParentSampleTable] 
        FOREIGN KEY (ParentSampleTableID) REFERENCES dbo.ParentSampleTable ([ID])
)
GO

ALTER TABLE dbo.SampleTable 
    NOCHECK CONSTRAINT [FK_SampleTable_ParentSampleTable]
GO

相关问题