Sql Server语法归纳

扶醉桌前 提交于 2020-02-13 22:41:12

Sql Server 语法

第一类

一、创建表结构CREATE TABLE

使用CREATE TABLE语句创建数据库的基本语法格式如下。

CREATE  TABLE  <表名>

 ( <列名>  <数据类型>

 [ NULL | NOT NULL ] [ IDENTITY [( seed ,increment ) ]  [{<列约束>}]

 [,…n]

)

 参数说明如下:

[NULL | NOT NULL ]:指定列的为空性,默认值为NOT NULL。

[IDENTITY  ( seed , increment ) ]:指定为标识列,seed为标示种子,increment为递增量。

【例】在销售管理数据库中,利用 Create Table语句,创建部门表和商品表。

USE  CompanySales

GO

CREATE TABLE  Department                - -创建部门表

( DepartmentID  int  NOT NULL,

         DepartmentName   varchar (30) NOT NULL,

         Manager char(8)   NULL,

         Depart_Description   varchar (50) NULL

 )

GO

CREATE TABLE  product                      - -创建商品表

(  ProductID  int NOT NULL,

    ProductName varchar(50)  NOT NULL,

          Price  decimal(18, 2) NULL,

          ProductStockNumber  int NULL,

        ProductSellNumber  int NULL

)

例子

CREATE TABLE student

(stu_NO int identity(x,y) primary key,   

/* identity(起始值x,增量y)primary key 设置主键*/

Stu_name char(8),

sex char(2),

birth datetime   

)

二、修改表结构Alter Table

使用Alter Table 语句修改表结构

修改数据表的语法格式如下:
    ALTER TABLE table_name
    { [ ALTER COLUMN column_name
    { new data type [ ( precision [,scale ] ) ]
    [NULL | NOT NULL]
    | ADD
    { [ < column_definition > ] [,...n ]
    | DROP { [ CONSTRAINT ] constraint_name | COLUMN column_name }[,...n ]

增加列

例4.8:在部门数据表dapartment,在部门名称DepartmentName列后增加两列,“部门人数”列PersonNum,数据类型为int,允许为空;“办公地点”列Office,数据类型varchar(50),允许为空。

ALTER TABLE Department

Add

PersonNum int null,

Office varchar(50) null

删除列

例4.9:在部门数据表dapartment删除两列:“部门人数”列PersonNum;“办公地点”列Office。

ALTER TABLE Department

Drop Column PersonNum,Office

修改数据类型

例4.10:在部门数据表Dapartment中将 “部门经理”列Manager的数据类型改为varchar(20) 。

ALTER TABLE Department

ALTER Column Manager varchar(20)

例4.11:在部门数据表Dapartment中将 “部门经理”列Manager重命名为ManagerName.

Sp_rename ‘Dapartment.Manager’, ‘Dapartment. ManagerName’,COLUMN

三、删除数据表Drop Table

n  使用Drop Table 语句

Drop table<表名>

n  例4.13 删除部门表department

Use companySales

Go

Drop table deparment

go

四、重命名数据表

例4.14 将商品表Product重命名为newProduct

Use companySales

Sp_rename ‘product’,‘Newproduct’

第二类

约束

约束分类

主关键字约束(Primary Key Constraint)

外关键字约束(Foreign Key Constraint)

惟一约束(Unique Constraint)

检查约束(Check Constraint)

默认约束(Default Constraint)

一、         主键约束

在创建表同时主键约束

①   

CREATE TABLE Department

(Department_ID int not null primary key,

Department_Name varchar(30) not null,

Manager  char(8) not null,

Depart_Description varchar(50) null

)

 

②   

CREATE TABLE Department

(

Department_ID int not null,

Department_Name varchar(30) not null,

Manager  char(8) not null,

Depart_Description varchar(50) null,

Constraint pk_Product primary key clustered(Department_ID)

)

例:

在一张现有表上添加主键约束

ALTER TABLE<表名>

ADD CONSTRAINT 约束名 Primary key(列名[,…n])

Alter table Product

Add constraint pk_product primary key(ProductID)

Alter table Product

Drop constraint pk_product

二、         外键约束

语法格式:

CREATE  TABLE  <表名>

(列名  数据类型  为空性 

FOREIGN  KEY  REFERENCES ref_table (ref_column)

    )

其中,参数说明如下。

REFERENCES:参照

ref_table:主键表名,要建立关联的被参照表的名称

ref_column:主键列名

CREATE TABLE Sell_Order

(SellOrderID int not null Primary key,

ProductID int not null Foreign key references Product(ProductID),

SelledOrderNumber int  null,

EmployeeID  int not null foreign key references Employee(EmployeeID),

CustomerID int null foreign key references Customer(CustomerID)

)

CREATE TABLE Sell_Order1

(SellOrderID int not null Primary key,

ProductID int not null,

SelledOrderNumber int  null,

EmployeeID  int not null,

CustomerID int null,

Constraint  FK_SELL_Order_Customer  Foreign key(CustomerID) references Customer(CustomerID),

onstraint  FK_SELL_Order_Employee  Foreign key(EmployeeID) references Employee(EmployeeID),

onstraint  FK_SELL_Order_Product  Foreign key(ProductID) references Product(ProductID),

)

CREATE TABLE Purchase_Order

(

PurchaseOrderID int not null,

ProductID int not null,

PurchaseOrderNumber int  null,

EmployeeID  int not null,

ProviderID int null,

PurchaseOrderDate smalldatetime null,

Constraint PK_POrder Primary key(PurchaseOrderID),

Constraint FK_POrder_em Foreign key(EmployeeID) references Employee(EmployeeID),

Constraint FK_POrder_Prv  Foreign key(ProviderID) references Provider(ProviderID),

Constraint FK_POrder_PR  Foreign key(ProductID) references Product(ProductID),

)

三、       唯一约束

惟一约束与主键约束的区别 。

惟一性约束指定的列可以有NULL 属性。但主键约束所在的列则不允许;

一个表中可以包含多个惟一约束,而主键约束则只能有一个;

创建惟一约束

创建表的同时创建UNIQUE约束

在现有的表中添加惟一约束

ALTER TABLE Department

  add constraint un_departName unique(DepartmentName)

四、       检查约束

检查约束(CHECK约束)定义

          实际上是验证字段输入内容的规则,表示一个字段的输入内容必须满足CHECK约束的条件,若不满足,则数据无法正常输入。可以对每个列设置CHECK约束。

 创建检查约束

使用Transact-SQL 语句

语法结构:     

CONSTRAINT  约束名  CHECK  ( logical_expression ) [,…n]

【练习】在销售管理数据库中的商品表中,为了保证数据的质量,确保商品的价格为大于0的数,库存量和已销售量数据为非负数。

 

alter table Product

add constraint ck_ptn check(price>=0 and ProductSellNumber>=0 and ProductSellNumber>=0)

Alter table Customer

Add constraint ck_cust check(Emailaddress like '%@%')

五、       默认值约束

默认值约束(DEFAULT)用于确保域完整性,它提供了一种为数据表中任何一列提供默认值的手段。

 创建默认值约束:

使用Transact-SQL 语句创建默认值定义

语法:

CONSTRAINT  约束名  DEFAULT  constant_expression  FOR 列名

【练习】在销售管理数据库中的员工表中,新员工如果不到特定部门工作的话,新员工全部到“销售部”工作

 

设置默认值

 

create default df_Sysdate

as

GETDATE()

EXEC sp_bindefault 'df_Sysdate','Employee.HireDate'

EXEC sp_bindefault 'df_Sysdate','Sell_Order.SellOrderDate'

EXEC sp_bindefault 'df_Sysdate','Purchase_Order.PurchaseOrderDate'

 

设置默认值

 

EXEC sp_unbindefault 'Employee.HireDate'

EXEC sp_ unbindefault 'Sell_Order.SellOrderDate'

EXEC sp_ unbindefault 'Purchase_Order.PurchaseOrderDate'

drop default df_Sysdate

 

规则 rule

创建规则

 

Create rule 规则名 AS 条件

create rule RL_Date as(@date>='1980-1-1' and @date<=getdate())

exec sp_bindrule 'RL_Date','Employee.HireDate'

 

删除规则:

 

exec sp_unbindrule 'Employee.HireDate'

exec sp_unbindrule 'Employee.HireDate'

drop rule RL_Date

第三类

数据表的操作

在SQL Server200X中,经过创建表确定基本结构以后,接着就是表中的数据处理:添加、修改和删除数据。

 

一、    插入记录

INSERT语句通常有两种形式:一种是插入一条记录;另一种是插入子查询的结果,一次可以插入多条记录。

INSERT语句语法插入一条记录,  格式 :

INSERT  [INTO]  表名  [(column_list)]

VALUES  ( { DEFAULT |NULL |expression }[,...n] )

Insert Customer(CustomerID,CompanyName,ContactName) values(34,'人民低压电器','南辉')

INSERT语句语法插入一条记录,  格式 :

INSERT  [INTO]  表名  [(column_list)]

VALUES  ( { DEFAULT |NULL |expression }[,...n] )

insert Department values(1,'销售部','王丽丽','主管销售')

insert Department values(2,'采购部','李嘉明','主管公司的产品采购')

insert Department values(3,'人事部','蒋柯南','主管公司的人事关系')

insert Department values(4,'后勤部','张绵荷','主管公司的后勤工作')

insert Department values(5,'保安部','贺妮玉','主管公司的安全问题')

插入多条记录

INSERT  [INTO]  表名  [(column_list)]

SELECT column_list  FROM  table_list 

WHERE search_condition

create table day_total(销售日期 datetime,销售数量 int)

insert into day_total select sellorderdate,COUNT(*) from Sell_Order group by SellOrderDate

SELECT * INTO Sell_Order1 FROM Sell_Order

二、    修改记录

语法格式:

UPDATE   表名  

SET  column_name=value [,column_name=value]

[FROM  table_name]

[WHERE  condition ]

【练习】在销售管理数据库中,将商品表中所有的商品的价格上调20%。

Update Product set price=price*1.2

【练习】将商品表product,所有库产量小于10商品的库存量清为0。

update Product set ProductStockNumber=0 where ProductStockNumber<10

三、    删除记录

在表删除数据时,可以用DELETE语句来实现,其语法格式如下。

DELETE   [FROM]   表名

[WHERE  condition]

其中,condition指定删除行的条件。

【练习】将商品表product,删除所有库产量为0的商品。

delete Product where ProductStockNumber=0

第四类

查询信息  SELECT语句

SELECT语句语法格式

 

SELECT <输出列表>

[INTO  <新表名>]

FROM  数据源列表

[ WHERE <查询条件表达式> ]

[GROUP BY <分组表达式>  [HAVING  <过滤条件> ] ]

[ ORDER BY <排序表达式>  [ ASC | DESC ] ]

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!