SQL Server primary key foreign key add and determine if table exists

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.