如何在SQL中将外键设为NULLABLE?

时间:2013-12-26 15:19:47

标签: sql sql-server sql-server-2005

    CREATE TABLE [M].[SocialInfo]
    (
        [Id] UNIQUEIDENTIFIER NOT NULL PRIMARY KEY DEFAULT newid(), 
[MemberId] UNIQUEIDENTIFIER  DEFAULT newid(),
    [GroupId] UNIQUEIDENTIFIER  DEFAULT newid(),
        [NewsURL] VARCHAR(200) NULL,     
        CONSTRAINT [FK_SocialInfo_Member] FOREIGN KEY ([MemberId]) REFERENCES [M].[Member]([Id]), 
        CONSTRAINT [FK_SocialInfo_Group] FOREIGN KEY ([GroupId]) REFERENCES [M].[Group]([Id]) 
    )
  

如何使两个FK都可以为空?

     

我无法获得语法?

3 个答案:

答案 0 :(得分:2)

我认为你刚刚遗漏了专栏文章。

CREATE TABLE [M].[SocialInfo]
(
    [Id] UNIQUEIDENTIFIER NOT NULL PRIMARY KEY DEFAULT newid(), 
    [NewsURL] VARCHAR(200) NULL,     
    MemberId INT NULL,
    GroupId INT NULL,
    CONSTRAINT [FK_SocialInfo_Member] FOREIGN KEY ([MemberId]) REFERENCES [M].[Member]([Id]), 
    CONSTRAINT [FK_SocialInfo_Group] FOREIGN KEY ([GroupId]) REFERENCES [M].[Group]([Id]) 
)

答案 1 :(得分:0)

外键的默认值没有意义 - 改为使用NULL

CREATE TABLE [M].[SocialInfo]
(
    [Id] UNIQUEIDENTIFIER NOT NULL PRIMARY KEY DEFAULT newid(), 
    [MemberId] UNIQUEIDENTIFIER  NULL,
    [GroupId] UNIQUEIDENTIFIER  NULL,
    [NewsURL] VARCHAR(200) NULL,     
    CONSTRAINT [FK_SocialInfo_Member] FOREIGN KEY ([MemberId]) REFERENCES [M].[Member]([Id]), 
    CONSTRAINT [FK_SocialInfo_Group] FOREIGN KEY ([GroupId]) REFERENCES [M].[Group]([Id]) 
)

答案 2 :(得分:0)