外键允许空SQL

时间:2014-01-03 13:00:34

标签: c# sql-server null foreign-keys

请检查这两张表。

create table Panda (id int identity, koalaId null) 
create table Koala (id int identity)

我需要koalaId是表考拉的外键 - >身份,但我还需要koalaId可以是NULL

在解决此问题后,我需要从Panda获取数据,但我只得到一个错误:

  

Panda的属性koalaId不能设置为null。必须将此属性设置为非空值且类型为Int32的值。

我希望koalaId设置为null

感谢您的建议。

2 个答案:

答案 0 :(得分:0)

默认情况下,外键列将允许空值。你不想明确提及它。

**for example:**
             Create table Kola(Id numeric identity(1,1) primary key)
             Create table Panda(Id numeric identity(1,1),
                                KolaId numeric references Kola(Id))

* 注意: *但请确保表'kola'中的列'id'在引用之前应该是主键 另一张桌子。

答案 1 :(得分:0)

这里是熊猫和可乐的创作代码:

    CREATE TABLE [dbo].[Kola](
        [id] [int] NOT NULL,
        [kolaName] [nchar](10) NULL,
      CONSTRAINT [PK_Kola] PRIMARY KEY CLUSTERED 
    (
        [id] 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

    CREATE TABLE [dbo].[Panda](
        [id] [int] NOT NULL,
        [KolaId] [int] NULL,
     CONSTRAINT [PK_Panda] PRIMARY KEY CLUSTERED 
    (
        [id] 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].[Panda]  WITH CHECK ADD  CONSTRAINT [FK_Panda_Kola] FOREIGN         KEY([KolaId])
    REFERENCES [dbo].[Kola] ([id])
    GO

    ALTER TABLE [dbo].[Panda] CHECK CONSTRAINT [FK_Panda_Kola]
    GO