如何将外键值插入到尚不存在的表中

时间:2014-07-03 11:26:02

标签: sql sql-server database rdbms

我有一个情况,我有两个表,即用户和公司。 这是我的用户表:

CREATE TABLE [dbo].[User](
[UserId] [int] IDENTITY(1,1) NOT NULL,
[UserName] [nvarchar](500) NOT NULL,
[Password] [nvarchar](500) NOT NULL,    
[CompanyId] [int] NULL,
[LastModUserId] [int] NOT NULL,
[LastModDttm] [datetime] NOT NULL,

CONSTRAINT [PK_User] PRIMARY KEY CLUSTERED 
(
  [UserId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[User]  WITH CHECK ADD  CONSTRAINT [FK_User_Company] FOREIGN KEY([CompanyId])
REFERENCES [dbo].[Company] ([CompanyId])
GO
ALTER TABLE [dbo].[User] CHECK CONSTRAINT [FK_User_Company]
GO

ALTER TABLE [dbo].[User]  WITH CHECK ADD  CONSTRAINT [FK_User_User1] FOREIGN KEY([LastModUserId])
REFERENCES [dbo].[User] ([UserId])
GO
ALTER TABLE [dbo].[User] CHECK CONSTRAINT [FK_User_User1]
 GO

这是我的公司表:

CREATE TABLE [dbo].[Company](
[CompanyId] [int] IDENTITY(1,1) NOT NULL,
[CompanyName] [nvarchar](500) NOT NULL,
[Address1] [nvarchar](500) NULL,
[Address2] [nvarchar](500) NULL,
[LastModUserId] [int] NOT NULL,
[LastModDttm] [datetime] NOT NULL,
CONSTRAINT [PK_Company] PRIMARY KEY CLUSTERED 
(
[CompanyId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,       ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
 ) ON [PRIMARY]

GO

ALTER TABLE [dbo].[Company]  WITH CHECK ADD  CONSTRAINT [FK_Company_User] FOREIGN KEY([LastModUserId])
REFERENCES [dbo].[User] ([UserId])
GO

ALTER TABLE [dbo].[Company] CHECK CONSTRAINT [FK_Company_User]
GO

我的问题:

我想创建公司记录,我还没有创建用户。当我插入LastModUserId columun时,它将抛出错误“无法将值NULL插入列'LastModUserId',表MYDb.dbo.Company ',列不允许nulls.INSERT失败。

如果我尝试将记录插入用户表,也存在同样的问题,有CompanyId列,它不允许空值

我该如何处理这种情况?

1 个答案:

答案 0 :(得分:1)

禁用约束以输入超级记录。

ALTER TABLE [User] NOCHECK CONSTRAINT [FK_User_User1];
     GO
     ALTER TABLE [User] NOCHECK CONSTRAINT [FK_User_Company];
     GO
     DECLARE @USERID AS INT, @COMPANYID AS INT;
     SELECT @USERID = 1, @COMPANYID = 1;
     SET IDENTITY_INSERT [User] ON;
     INSERT INTO [User](
     [UserId],
    [UserName],
    [Password],
    [CompanyId],
    [LastModUserId], 
    [LastModDttm]
    )
    select
    @USERID,
    'Super',
    'Passw0rd',
    1,
    1,
    getdate();

    SET IDENTITY_INSERT [User] OFF;

    SET IDENTITY_INSERT [Company] ON;

    insert into [Company](
    [CompanyId],
    [CompanyName],
    [Address1],
    [Address2],
    [LastModUserId],
    [LastModDttm])
    select
    @COMPANYID,
    'cOMANY a',
    'Address 1',
    'Address 2',
    @USERID,
    getdate();

    SET IDENTITY_INSERT [Company] OFF;
    go
     ALTER TABLE [User] CHECK CONSTRAINT [FK_User_User1];
     GO
     ALTER TABLE [User] CHECK CONSTRAINT [FK_User_Company];
     GO