SqlServer主键外键添加及判断表是否存在

GO
--判断表是否存在方式1
if object_id(N'EF_User',N'U') is null
--判断表是否存在方式2
--if not exists (select * from dbo.SysObjects WHERE id = object_id(N'[EF_User]') AND OBJECTPROPERTY(ID, 'IsTable') = 1) 
begin
--直接创建自增且指定主键约束的表
CREATE TABLE [dbo].[EF_User](
    [ID] [int] identity(1,1) not null,
    [loginName] [nvarchar](100) NULL,
    [realName] [nvarchar](100) NULL,
    [phoneNo] [nvarchar](100) NULL,
    CONSTRAINT [PK_User] PRIMARY KEY(ID)
)
--删除主键约束
alter table [dbo].[EF_User] drop constraint PK_User
--添加主键约束
alter table [dbo].[EF_User] add constraint PK_User primary key(ID)

end

GO
CREATE TABLE [dbo].[EF_Role](
    [ID] [int] identity(1,1) not null,
    [Name] [nvarchar](100) NULL,
    [remark] [nvarchar](100) NULL,
    constraint [PK_Role] Primary Key(ID)
) 

GO
CREATE TABLE [dbo].[EF_User_Role](
    [UserID] [int] NOT NULL,
    [RoleID] [int] NOT NULL
)
--添加外键约束
alter table EF_User_Role add constraint FK_User_Role_User foreign key (UserID)
references EF_User(ID)
alter table EF_User_Role add constraint FK_User_Role_Role foreign key (RoleID)
references EF_Role(ID)
GO

 

posted @ 2016-06-15 00:19  蒹葭白露  阅读(4407)  评论(0编辑  收藏  举报