数据库用seq语句从创建数据库到给表添加约束条件(改进)

介于原来这个博文的浏览量挺高的,今天闲来加上备注,虽然很基础,但是还是避免有些人看不懂,大失所望。

话不多说,来看代码:


USE master  //调用你想使用的数据库
Go
IF EXISTS (SELECT * FROM SYSDATABASES WHERE name = 'E_NEW') //如果存在名字叫做E_new的数据库
DROP DATABASE E_NEW //就删除这个数据库,不存在就跳过。
CREATE DATABASE E_NEW //创建数据库及设置
ON PRIMARY
(
NAME = 'E_NEW_DATA',
FILENAME = 'D:\SqlServer\E_NEW_DATA.mdf',
SIZE = 5MB,
MAXSIZE = 100MB,
FILEGROWTH = 15%
)
LOG ON //生成日志文件,及相关设置
(
NAME = 'E_NEW_LOG',
FILENAME = 'D:\SqlServer\E_NEW_LOG.ldf',
SIZE = 5MB,
FILEGROWTH = 0
)


SELECT * FROM SYS.databases WHERE name = 'E_NEW'
SELECT DATABASEPROPERTYEX('E_NEW', 'STATUS')//查看数据库的状态


EXEC sp_detach_db @dbname = 'E_NEW'  //分离数据库
go
EXEC sp_attach_db @dbname = 'E_NEW', //连接
@filename1 = 'D:\SqlServer\E_NEW_DATA.mdf',
@filename2 = 'D:\SqlServer\E_NEW_LOG.ldf'
GO

USE E_NEW //下面是建表,不多说了,结合数据库理解
GO
IF EXISTS (SELECT * FROM SYSOBJECTS WHERE name = 'UserInfo')
DROP TABLE UserInfo
GO
CREATE TABLE UserInfo
(
UserId varchar(20) NOT NULL,
UserPwd varchar(50) NOT NULL,
UserName varchar(50) NOT NULL,
Gender int NOT NULL,
Email varchar(50),
UserAdress nvarchar(200),
Phone varchar(20) NOT NULL
)
GO


--给表添加约束
USE E_NEW
GO
ALTER TABLE UserInfo
ADD CONSTRAINT PK_UserId PRIMARY KEY(UserId), //设置主键,种子
CONSTRAINT CK_UserPwd CHECK(LEN(UserPwd)>= 6), //这是设置密码长度必须>=6,constraint后面是自己起的名字
CONSTRAINT CK_Gender CHECK (Gender = 0 or Gender = 1), //性别只能填写0和1代表男和女
CONSTRAINT DK_Gender DEFAULT(0) FOR Gender,
CONSTRAINT CK_Email CHECK(Email LIKE '%@%') //邮箱地址必须有“@”符号
GO


--订单表
USE E_NEW
GO
CREATE TABLE OrderInfo1
(
OrderId int IDENTITY(1,1) NOT NULL,
UserId varchar(20) NOT NULL,
CommodityId int NOT NULL, --商品编号
Amount int NOT NULL,
PayMoney bigint NOT NULL,
PayWay varchar(50) NOT NULL,
OrderTime datetime NOT NULL,
Confirm int NOT NULL,
SendGoods int NOT NULL
)
GO
--添加外键约束时,注意:
--1.类型 长度必须与引用的主键的类型长度一致
--2.引用的表中必须有主键列


--为上边的订单表添加约束
USE E_NEW
GO
ALTER TABLE OrderInfo
ADD CONSTRAINT PK_OrderId PRIMARY KEY(OrderId),
CONSTRAINT FK_UserId FOREIGN KEY (UserId) REFERENCES UserInfo (UserId),
CONSTRAINT DK_PayWay DEFAULT('网上银行') FOR PayWay,
CONSTRAINT CK_Confirm CHECK (Confirm = 0 or Confirm = 1),
CONSTRAINT DK_Confirm DEFAULT(0) FOR Confirm,
CONSTRAINT CK_SendGoods CHECK (SendGoods = 0 or SendGoods = 1),
CONSTRAINT DK_SendGoods DEFAULT(0) FOR SendGoods
GO

你可能感兴趣的:(数据库用seq语句从创建数据库到给表添加约束条件(改进))