GO--determine if the table exists in the way 1if object_id(N'Ef_user'N'U') is NULL--determine if the table exists in the way 2--If not EXISTS (SELECT * FROM dbo. SysObjects WHERE id = object_id (N ' [Ef_user] ') and OBJECTPROPERTY (ID, ' istable ') = 1)begin--directly create a table with the self-increment and specify a PRIMARY KEY constraintCREATE TABLE [dbo].[Ef_user]( [ID] [int] Identity(1,1) not NULL, [LoginName] [nvarchar]( -)NULL, [Realname] [nvarchar]( -)NULL, [Phoneno] [nvarchar]( -)NULL, CONSTRAINT [Pk_user] PRIMARY KEY(ID))--Delete a primary KEY constraintAlter Table [dbo].[Ef_user] Drop constraintPk_user--Add a PRIMARY KEY constraintAlter Table [dbo].[Ef_user] Add constraintPk_userPrimary Key(ID)EndGOCREATE TABLE [dbo].[Ef_role]( [ID] [int] Identity(1,1) not NULL, [Name] [nvarchar]( -)NULL, [Remark] [nvarchar]( -)NULL, constraint [Pk_role] Primary Key(ID))GOCREATE TABLE [dbo].[Ef_user_role]( [UserID] [int] not NULL, [Roleid] [int] not NULL)--Add a FOREIGN KEY constraintAlter TableEf_user_roleAdd constraintFk_user_role_userForeign Key(UserID)ReferencesEf_user (ID)Alter TableEf_user_roleAdd constraintFk_user_role_roleForeign Key(Roleid)Referencesef_role (ID)GO
SQL Server primary key foreign key add and determine if table exists