当前位置: 数据库>sqlserver
SQL MSSQL 常用代码大全
来源: 互联网 发布时间:2014-09-05
本文导语: /*********************************************************/ function:SQL MSSQL TECHNOLOGY ARTICLE file :SQL-MSSQL.TXT author :chinayaosir QQ:44633197 Tools :MSSQL QUERY ANALYSIS date :4/01/2010 blog :http://blog.csdn.net/chinayaosir note :禁止其它网站转载此文章 /***********************...
/*********************************************************/
function:SQL MSSQL TECHNOLOGY ARTICLE
file :SQL-MSSQL.TXT
author :chinayaosir QQ:44633197
Tools :MSSQL QUERY ANALYSIS
date :4/01/2010
blog :http://blog.csdn.net/chinayaosir
note :禁止其它网站转载此文章
/*********************************************************/
目录清单CONTEXT LIST
/*********************************************************/
1.数据库DataBase
1.1数据库建立/删除create/drop database
1.2数据库备份与恢复backup/restore database
/*********************************************************/
2.数据查询DATA QUERY LANGUAGE
2.1选择查询Select Query
2.2聚集查询Aggregate Query
2.3子查询 Sub Query
2.4连接查询Table Joins
2.5汇总查询Group Query
/*********************************************************/
3.数据修改DATA MODIFY LANGUAGE
3.1插入数据Insert
3.2修改数据Update
3.3删除数据Delete
/*********************************************************/
4.数据定义DATA DEFINE LANGUAGE
4.1表Table
4.2列Column
4.3序列Identity
4.4约束Constraints
4.5索引Index
4.6视图view
4.7权限Privilege
/*********************************************************/
5.数据库函数Functions
5.1转换函数Data Convert Functions
5.2聚集函数Aggregate Functions
5.3字符函数char Functions
5.4日期函数Date Functions
5.5数学函数Math Functions
5.6分析函数Analytical Functions
/*********************************************************/
6.数据库脚本Script
6.1数据类型Data Types
6.2脚本语法Statements
6.3脚本游标Cursor
6.4存储过程Procedure
6.5存储函数Function
6.6触发器Trigger
6.7事务Transaction
6.8其它Other
/*********************************************************/
SQL明细 SQL DETAIL
/**********************************************************/
1.数据库DataBase
1.1数据库建立/删除create/drop database
1.2备份与恢复backup/restore database
/**********************************************************/
1.1数据库建立/删除create/drop database
1.1.1.建立数据库
语法:create database [其它参数]
代码:
//建立数据库 hr
create database hr
1.1.2.删除数据库。
语法:drop database
代码:
//删除数据库hr
drop database hr
//如果存在hr数据库,则删除数据库hr
IF DB_ID('hr') IS NOT NULL
DROP DATABASE TestDB
-----------------------------------------------------------
1.2备份与恢复backup/restore database
1.2.1.添加备份设备
语法:sp_addumpdevice
代码:
//添加备份设备为本地硬盘
sp_addumpdevice 'disk', 'localbackup', 'e:databasebackuplocalbak.bak'
//备份到网络硬盘
sp_addumpdevice 'disk', 'netbackup', '\computer1databasebackupnetbak.bak'
//备份到磁带
sp_addumpdevice 'tape', 'tapebackup', '\.tape1bak'
//备份到命名管道
sp_addumpdevice 'pipe', 'pipebackup', 'e:databasebackuppipebak'
1.2.2.备份数据库
语法:backup database to | disk=
代码:
//备份数据库到备份设备
backup database pubs to localbackup
//备份数据库到指定路径下面的指定文件
backup database pubs to disk='e:databasebackuppubsbak.bak'
1.2.3.恢复数据库
语法:restore database from | disk=
代码:
//从备份设备中恢复数据库
restore database pubs from localbackup
//从备份文件中恢复数据库
/**********************************************************/
2.数据查询DATA QUERY LANGUAGE
2.1选择查询Select Query
2.2子查询 Sub Query
2.3连接查询Table Joins
2.4汇总查询Group Query
-----------------------------------------------------------
2.1选择查询Select Query
语法:
select [top n][/all]/[distinct] [*] / [columnlist...] [,=,,=, (select sum(quota) from salesreps where rep_office=office)
//列出超过销售目标的销售点的业务人员[in测试]
select name from salesreps where office in (select office from offies where sales > target)
//列出订单大于2500元的产品名称[exists测试]
select description from products where exists (
select * from orders where product=prodct_id and amount > 2500.00
)
//列出完成销售目标10%的销售人员清单[any测试]
select name from salesreps where (0.1* quota) < any(select amount from orders where rep=empl_num)
-----------------------------------------------------------
2.3连接查询Table Joins
多表连接类型可分为三类(内/外/交叉连接)
主从表或者父子表进行多表连接多以主键和外键进行关联
Outer joins(LEFT OUTER, RIGHT OUTER, and FULL OUTER joins)
left outer join:查询的结果以左边表行数为准
right outer join:查询的结果以右边表行数为准
2.3.1.内连接inner join
功能:
语法:
SELECT select_list
FROM table_1
[INNER] JOIN table_2
ON join_condition_1
[[INNER] JOIN table_3
ON join_condition_2]...
代码:
//没有where子句的内连接
SELECT *
FROM Products
INNER JOIN Suppliers
ON Products.SupplierID = Suppliers.SupplierID
//有where子句的内连接
SELECT p.ProductID, s.SupplierID, p.ProductName, s.CompanyName
FROM Products p
INNER JOIN Suppliers s
ON p.SupplierID = s.SupplierID
WHERE p.ProductID < 4
-----------------------------------------------------------
2.3.2.外连接outer join
功能:包括三种连接LEFT OUTER, RIGHT OUTER, and FULL OUTER joins
left outer :查询的结果以左边表行数为准
right outer :查询的结果以右边表行数为准
语法:select ... from table1 [left/right/full outer join ]table2 where ...
代码:
//以Customers表行数为标准去连接Orders表
SELECT c.CustomerID, CompanyName
FROM Customers c
LEFT OUTER JOIN Orders o
ON c.CustomerID = o.CustomerID
WHERE o.CustomerID IS NULL
-----------------------------------------------------------
2.3.3.交叉连接cross join
功能:以主从表或者父子表之间的主键进行连接,最终以笛卡尔乘积运算的结果
语法:select ... from table1 cross join table2 where ...
代码:
//显示结果以表1行数*表2行数
假设Departments为4行记录
假设Jobs为3行记录
下面的显示结果为4*3=12行记录
SELECT deptname,jobdesc FROM Departments CROSS JOIN Jobs
//用关键字匹配的交叉连接
oc_head/oc_detail是主从表
oc_head(主键oc_number)
oc_detail(主键oc_number,item_number,ship_date)
SELECT h.customerid,d.item_number,d.ship_date
from oc_head as h CROSS JOIN oc_detail as d
where h.oc_number=d.oc_number
-----------------------------------------------------------
2.4汇总查询Group Query
//汇总查询相当于会计报表中的小计汇总的功能
语法: select ...
from
group by
[having search expression]
代码:
//求出每名销售人员的销售金额
select rep,sum(amount) from orders group by rep
//每个销售点分配了多少销售人员
select rep_office,count(*) from salesreps group by rep_office
//计算每名销售人员的每个客户和订单金额
select cust,rep,sum(amount) from orders group by cust,rep
//Having子句应用
select rep,avg(amount) from orders having sum(quota) > 3000.00
/**********************************************************/
3.数据修改DATA MODIFY LANGUAGE
3.1插入数据Insert
3.2修改数据Update
3.3删除数据Delete
-----------------------------------------------------------
3.1插入数据Insert
3.1.1.单行插入
语法:insert into [...] values(...);
代码:
//不省略字段清单
insert into salesreps(name,age,empl_no,sales,title,hire_date,rep_office)
values('jack toms',36,111,0.00,'sales mgr','10-05-2010',13)
//省略字段清单
insert into salesreps
values('jack toms',36,111,0.00,'sales mgr','10-05-2010',13)
3.1.2.多行插入
语法:insert into [(...)] values(...) ;
代码:
//把一批数据批量插入到一个备份表中
insert into history_order(order_num,order_date,amount)
select order_num,order_date,amount
from orders where order_date < '01/01/2000'
-----------------------------------------------------------
3.2修改数据Update
语法:update set (cloumn=expression...) [where ...] [SubQuery..]
代码:
//更新所有记录
update salesreps set quota=1.05 * quota
//按条件更新表记录
update salesreps set quota=1.08 * quota where area='china'
//按子查询更新表记录
update customers set cust_rep=105
where cust_rep in (
selct empl_num from salesreps where sales < (0.8 * quota)
)
-----------------------------------------------------------
3.3删除数据Delete
语法1:delete from [where ...]
代码:
//所有删除记录
delete from orders
语法2:truncate table
代码2:
//所有删除记录
truncate table orders
//按条件删除记录
delete from orders where order_date < '01/01/2000'
/**********************************************************/
4.数据定义DATA DEFINE LANGUAGE
4.1表Table
4.2列Column
4.3序列Indentity
4.4约束Constraints
4.5索引Index
4.6视图view
4.7权限Privilege
/**********************************************************/
4.1表Table
4.1.1.建立表
语法:
create table (
[长度]
)
代码:
//建立公司部门表
create table tb_basic_dept(
id int not null,
name varchar(20) ,
chair varchar(20)
)
4.1.2.删除表
语法:
drop table
代码:
//删除部门表
drop table tb_basic_dept
-----------------------------------------------------------
4.2列Column
4.2.1.列添加
语法:
alter table add
[长度]
代码:
alter table tb_basic_dept add
remark varchar(50)
4.2.2.列删除
语法:alter table drop column
代码:
alter table tb_basic_dept drop column remark
4.2.3.列修改
语法:alter table alter column
[长度] [null | not null]
代码:
//修改工资列为dec(8,2)
alter table tb_hr_gz alter column gz dec(8,2) null
-----------------------------------------------------------
4.3序列Identity
//特别要求
IDENTITY字段数据类型只能是(int, bigint, smallint, tinyint, decimal, or numeric(x,0))
IDENTITY字段必须是not null约束
4.3.1Identity
语法:
IDENTITY( [, , ]) AS column_name,
代码:
//使用Identity
CREATE TABLE MyTable (
key_col int NOT NULL IDENTITY (1,1),
abc char(1) NOT NULL
)
INSERT INTO MyTable VALUES ('a')
INSERT INTO MyTable VALUES ('b')
INSERT INTO MyTable VALUES ('c')
-----------------------------------------------------------
4.4约束Constraints
4.4.1缺省约束(default)
4.4.2非空约束(not null)
4.4.3规则约束(rule)
4.4.4检查约束(check)
4.4.5唯一约束(unique)
4.4.6主键约束(primary key)
4.4.7外键约束(foreign key)
4.4.8商业规则(business rule)
以下面两个表为例进行演示
create table tb_hr_bm(
bm varchar(20) not null ,
remark varchar(100) default ''
)
create table tb_hr_gz(
id int not null,
name varchar(30) not null,
hrid char(18) null,
workage int null ,
bm varchar(20) null,
gz real null,
remark varchar(100) null
)
hrid=身份证号码
workage=工作年数
gz=工资金额
-----------------------------------------------------------
4.4.1缺省约束(default)
语法:CREATE DEFAULT default_name AS expression
代码:CREATE DEFAULT zip_default AS 94710
-----------------------------------------------------------
4.4.2非空约束(not null)
//表的主键和其它必填字段必须为not null.
语法:create table (column-name datatype not null... )
代码:create table tb_hr_gz(id int not null,...)
-----------------------------------------------------------
4.4.3规则约束(rule)
语法:CREATE RULE rulename AS condition
代码:
//邮编号码6位100000-999999
//建立一个自定义zip类型
CREATE TYPE zip FROM CHAR(6) NOT NULL
//建立一个规则约束
CREATE RULE zip_rule AS @number >100000 and @number < 999999
//绑定规则约束到zip类型
EXEC sp_bindrule zip_rule, 'zip'
//应用自定义zip类型
2> CREATE TABLE address(
city CHAR(25) NOT NULL,
zip_code ZIP,
street CHAR(30) NULL
)
-----------------------------------------------------------
4.4.4检查约束(建立/删除)
//检查约束建立
语法:
alter table name
add constraint check
代码:
//工资添加取值范围0 ~ 1000000
方法1:
create table tb_hr_gz(
gz real default 0.0 check(gz >=0 and gz =0 and gz @y
print 'x > y' --打印字符串'x > y'
else if @y > @z
print 'y > z'
else print 'z > y'
6.2.3.2 CASE语句
--CASE
use pangu
update employee
set e_wage =
case
when job_level = '1' then e_wage*1.08
when job_level = '2' then e_wage*1.07
when job_level = '3' then e_wage*1.06
else
e_wage*1.05
end
6.2.4循环语句(while)
--WHILE
declare @x int @y int @c int
select @x = 1 @y=1
while @x < 3
begin
print @x --打印变量x 的值
while @y < 3
begin
select @c = 100*@x + @y
print @c --打印变量c 的值
select @y = @y + 1
end
select @x = @x + 1
select @y = 1
end
6.2.5定时执行(waitfor)
--WAITFOR
--例 等待1 小时2 分零3 秒后才执行SELECT 语句
waitfor delay '01:02:03'
select * from employee
--例 等到晚上11 点零8 分后才执行SELECT 语句
waitfor time '23:08:00'
select * from employee
-----------------------------------------------------------
6.3脚本游标Cursor
//游标应用顺序
1.DECLARE --为查询设定游标
2.OPEN --检索查询结果打开一个游标
3.FETCH --检索一行查询结果
4.CLOSE / DEALLOCATE--关闭游标或者重新分配游标
语法:
DECLARE CURSOR FOR(select sql)
OPEN
while @@fetch_status = 0
begin
FETCH NEXT FROM INTO
{其它代码处理}
end
CLOSE
代码1:
/*带游标的存储过程*/
create procedure p_fill_remark_tb_hr_gz
as
declare @id1 int
declare @name1 varchar(30)
declare @bm1 varchar(20)
begin
declare cursor1 cursor for select id,name,bm from tb_hr_gz
open cursor1
fetch next from cursor1 into @id1,@name1,@bm1
while @@fetch_status 0
begin
update tb_hr_gz set remark=@name1+'-'+@bm1 where id=@id1
fetch next from cursor1 into @id1,@name1,@bm1
end
close cursor1
end
//测试带游标的存储过程
EXEC dbo.p_fill_remark_tb_hr_gz
-----------------------------------------------------------
6.4存储过程Procedure
//存储过程建立
语法:
create procedure (
[输入参数列表],[返回参数列表 output]
)
as
[局部变量定义]
begin
{语句体}
end
代码:
create procedure p_update_name_tb_hr_gz(@id int,@newname varchar(30))
as
begin
if (exists(select * from tb_hr_gz where id=@id))
begin
update tb_hr_gz set name=@newname where id=@id
end
end
//测试
EXEC dbo.p_update_name_tb_hr_gz '112','chenglei'
//存储过程删除
语法:
drop procedure
代码:
drop procedure p_update_name_tb_hr_gz
-----------------------------------------------------------
6.5存储函数Function
//存储函数建立
语法:
CREATE FUNCTION (参数变量列表)
[返回值RETURNS 数据类型] [WITH ENCRYPTION]
AS
BEGIN
{函数代码体....}
END
代码:
//函数f_amt_to_eng()功能:数字金额转换为英文字母金额
CREATE FUNCTION f_amt_to_eng(@num numeric(15,2))
RETURNS varchar(400) WITH ENCRYPTION
AS
BEGIN
DECLARE @i int,@hundreds int,@tenth int,@one int
DECLARE @thousand int,@million int,@billion int
DECLARE @numbers varchar(400),@s varchar(15),@result varchar(400)
SET @numbers='one two three four five '
+'six seven eight nine ten '
+'eleven twelve thirteen fourteen fifteen '
+'sixteen seventeen eighteen nineteen '
+'twenty thirty forty fifty '
+'sixty seventy eighty ninety '
SET @s=RIGHT('000000000000000'+CAST(@num AS varchar(15)),15)
SET @billion=CAST(SUBSTRING(@s,1,3) AS int)--将12位整数分成4段:十亿、百万、千、百十个
SET @million=CAST(SUBSTRING(@s,4,3) AS int)
SET @thousand=CAST(SUBSTRING(@s,7,3) AS int)
SET @result=''
SET @i=0
WHILE @i0 or @thousand>0 or @hundreds>0)) or
(@i=2 and (@billion>0 or @million>0) and (@thousand>0 or @hundreds>0)) or
(@i=3 and (@billion>0 or @million>0 or @thousand>0) and (@hundreds>0))
SET @result=@result+', '--百位不是0则每段之间加连接符,
IF (@i=3 and (@billion>0 or @million>0 or @thousand>0) and (@hundreds=0 and (@tenth>0 or @one>0)))
SET @result=@result+' and '--百位是0则加连接符AND
IF @hundreds>0
SET @result=@result+RTRIM(SUBSTRING(@numbers,@hundreds*10-9,10))+' hundred'
IF @tenth>=2 and @tenth0
SET @result=@result+' and '
SET @result=@result+RTRIM(SUBSTRING(@numbers,@tenth*10+171,10))
END
IF @one>=1 and @one0
SET @result=@result+'-'
ELSE
IF @hundreds>0
SET @result=@result+' and '
SET @result=@result+RTRIM(SUBSTRING(@numbers,@one*10-9,10))
END
IF @i=0 and @billion>0
SET @result=@result+' billion'
IF @i=1 and @million>0
SET @result=@result+' million'
IF @i=2 and @thousand>0
SET @result=@result+' thousand'
SET @i=@i+1
END
IF SUBSTRING(@s,14,2)'00'
BEGIN
SET @result=@result+' AND '
IF SUBSTRING(@s,14,1)='0'
SET @result=@result+'zero'
ELSE
SET @result=@result+RTRIM(SUBSTRING(@numbers,CAST(SUBSTRING(@s,14,1) AS int)*10-9,10))
IF SUBSTRING(@s,15,1)'0'
SET @result=@result+' '+RTRIM(SUBSTRING(@numbers,CAST(SUBSTRING(@s,15,1) AS int)*10-9,10))
END
RETURN(@result)
END
CREATE FUNCTION f_amt_to_chn (@num numeric(14,2))
RETURNS varchar(100) WITH ENCRYPTION
AS
BEGIN
DECLARE @n_data VARCHAR(20),@c_data VARCHAR(100),@n_str VARCHAR(10),@i int
SET @n_data=RIGHT(SPACE(14)+CAST(CAST(ABS(@num*100) AS bigint) AS varchar(20)),14)
SET @c_data=''
SET @i=1
WHILE @i
sql server 2005 三个常用的小sql
access与sql server几个常用函数的区别(图文)
T-SQL常用的聚合函数
oracle 常用的几个SQL
T-SQL常用的数学函数
Oracle 常用的SQL语句
SQL 提权 常用命令
sql server 常用的几个数据类型
T-SQL常用的元数据函数
T-SQL常用的时间和日期函数
iis7站长之家
T-SQL常用的时间和日期函数
sql日期格式转换方法汇总(常用)
sql 常用临时表的区别(实例演示)
SQL Server 设置主键自增长列的常用代码
[Oracle] 常用工具集之SQL*Loader的用法
mysql建表常用sql语句个人经验分享
T-SQL常用的系统函数
Yii调试SQL的常用方法
一些常用的更改表字段的sql语句
function:SQL MSSQL TECHNOLOGY ARTICLE
file :SQL-MSSQL.TXT
author :chinayaosir QQ:44633197
Tools :MSSQL QUERY ANALYSIS
date :4/01/2010
blog :http://blog.csdn.net/chinayaosir
note :禁止其它网站转载此文章
/*********************************************************/
目录清单CONTEXT LIST
/*********************************************************/
1.数据库DataBase
1.1数据库建立/删除create/drop database
1.2数据库备份与恢复backup/restore database
/*********************************************************/
2.数据查询DATA QUERY LANGUAGE
2.1选择查询Select Query
2.2聚集查询Aggregate Query
2.3子查询 Sub Query
2.4连接查询Table Joins
2.5汇总查询Group Query
/*********************************************************/
3.数据修改DATA MODIFY LANGUAGE
3.1插入数据Insert
3.2修改数据Update
3.3删除数据Delete
/*********************************************************/
4.数据定义DATA DEFINE LANGUAGE
4.1表Table
4.2列Column
4.3序列Identity
4.4约束Constraints
4.5索引Index
4.6视图view
4.7权限Privilege
/*********************************************************/
5.数据库函数Functions
5.1转换函数Data Convert Functions
5.2聚集函数Aggregate Functions
5.3字符函数char Functions
5.4日期函数Date Functions
5.5数学函数Math Functions
5.6分析函数Analytical Functions
/*********************************************************/
6.数据库脚本Script
6.1数据类型Data Types
6.2脚本语法Statements
6.3脚本游标Cursor
6.4存储过程Procedure
6.5存储函数Function
6.6触发器Trigger
6.7事务Transaction
6.8其它Other
/*********************************************************/
SQL明细 SQL DETAIL
/**********************************************************/
1.数据库DataBase
1.1数据库建立/删除create/drop database
1.2备份与恢复backup/restore database
/**********************************************************/
1.1数据库建立/删除create/drop database
1.1.1.建立数据库
语法:create database [其它参数]
代码:
//建立数据库 hr
create database hr
1.1.2.删除数据库。
语法:drop database
代码:
//删除数据库hr
drop database hr
//如果存在hr数据库,则删除数据库hr
IF DB_ID('hr') IS NOT NULL
DROP DATABASE TestDB
-----------------------------------------------------------
1.2备份与恢复backup/restore database
1.2.1.添加备份设备
语法:sp_addumpdevice
代码:
//添加备份设备为本地硬盘
sp_addumpdevice 'disk', 'localbackup', 'e:databasebackuplocalbak.bak'
//备份到网络硬盘
sp_addumpdevice 'disk', 'netbackup', '\computer1databasebackupnetbak.bak'
//备份到磁带
sp_addumpdevice 'tape', 'tapebackup', '\.tape1bak'
//备份到命名管道
sp_addumpdevice 'pipe', 'pipebackup', 'e:databasebackuppipebak'
1.2.2.备份数据库
语法:backup database to | disk=
代码:
//备份数据库到备份设备
backup database pubs to localbackup
//备份数据库到指定路径下面的指定文件
backup database pubs to disk='e:databasebackuppubsbak.bak'
1.2.3.恢复数据库
语法:restore database from | disk=
代码:
//从备份设备中恢复数据库
restore database pubs from localbackup
//从备份文件中恢复数据库
/**********************************************************/
2.数据查询DATA QUERY LANGUAGE
2.1选择查询Select Query
2.2子查询 Sub Query
2.3连接查询Table Joins
2.4汇总查询Group Query
-----------------------------------------------------------
2.1选择查询Select Query
语法:
select [top n][/all]/[distinct] [*] / [columnlist...] [,=,,=, (select sum(quota) from salesreps where rep_office=office)
//列出超过销售目标的销售点的业务人员[in测试]
select name from salesreps where office in (select office from offies where sales > target)
//列出订单大于2500元的产品名称[exists测试]
select description from products where exists (
select * from orders where product=prodct_id and amount > 2500.00
)
//列出完成销售目标10%的销售人员清单[any测试]
select name from salesreps where (0.1* quota) < any(select amount from orders where rep=empl_num)
-----------------------------------------------------------
2.3连接查询Table Joins
多表连接类型可分为三类(内/外/交叉连接)
主从表或者父子表进行多表连接多以主键和外键进行关联
Outer joins(LEFT OUTER, RIGHT OUTER, and FULL OUTER joins)
left outer join:查询的结果以左边表行数为准
right outer join:查询的结果以右边表行数为准
2.3.1.内连接inner join
功能:
语法:
SELECT select_list
FROM table_1
[INNER] JOIN table_2
ON join_condition_1
[[INNER] JOIN table_3
ON join_condition_2]...
代码:
//没有where子句的内连接
SELECT *
FROM Products
INNER JOIN Suppliers
ON Products.SupplierID = Suppliers.SupplierID
//有where子句的内连接
SELECT p.ProductID, s.SupplierID, p.ProductName, s.CompanyName
FROM Products p
INNER JOIN Suppliers s
ON p.SupplierID = s.SupplierID
WHERE p.ProductID < 4
-----------------------------------------------------------
2.3.2.外连接outer join
功能:包括三种连接LEFT OUTER, RIGHT OUTER, and FULL OUTER joins
left outer :查询的结果以左边表行数为准
right outer :查询的结果以右边表行数为准
语法:select ... from table1 [left/right/full outer join ]table2 where ...
代码:
//以Customers表行数为标准去连接Orders表
SELECT c.CustomerID, CompanyName
FROM Customers c
LEFT OUTER JOIN Orders o
ON c.CustomerID = o.CustomerID
WHERE o.CustomerID IS NULL
-----------------------------------------------------------
2.3.3.交叉连接cross join
功能:以主从表或者父子表之间的主键进行连接,最终以笛卡尔乘积运算的结果
语法:select ... from table1 cross join table2 where ...
代码:
//显示结果以表1行数*表2行数
假设Departments为4行记录
假设Jobs为3行记录
下面的显示结果为4*3=12行记录
SELECT deptname,jobdesc FROM Departments CROSS JOIN Jobs
//用关键字匹配的交叉连接
oc_head/oc_detail是主从表
oc_head(主键oc_number)
oc_detail(主键oc_number,item_number,ship_date)
SELECT h.customerid,d.item_number,d.ship_date
from oc_head as h CROSS JOIN oc_detail as d
where h.oc_number=d.oc_number
-----------------------------------------------------------
2.4汇总查询Group Query
//汇总查询相当于会计报表中的小计汇总的功能
语法: select ...
from
group by
[having search expression]
代码:
//求出每名销售人员的销售金额
select rep,sum(amount) from orders group by rep
//每个销售点分配了多少销售人员
select rep_office,count(*) from salesreps group by rep_office
//计算每名销售人员的每个客户和订单金额
select cust,rep,sum(amount) from orders group by cust,rep
//Having子句应用
select rep,avg(amount) from orders having sum(quota) > 3000.00
/**********************************************************/
3.数据修改DATA MODIFY LANGUAGE
3.1插入数据Insert
3.2修改数据Update
3.3删除数据Delete
-----------------------------------------------------------
3.1插入数据Insert
3.1.1.单行插入
语法:insert into [...] values(...);
代码:
//不省略字段清单
insert into salesreps(name,age,empl_no,sales,title,hire_date,rep_office)
values('jack toms',36,111,0.00,'sales mgr','10-05-2010',13)
//省略字段清单
insert into salesreps
values('jack toms',36,111,0.00,'sales mgr','10-05-2010',13)
3.1.2.多行插入
语法:insert into [(...)] values(...) ;
代码:
//把一批数据批量插入到一个备份表中
insert into history_order(order_num,order_date,amount)
select order_num,order_date,amount
from orders where order_date < '01/01/2000'
-----------------------------------------------------------
3.2修改数据Update
语法:update set (cloumn=expression...) [where ...] [SubQuery..]
代码:
//更新所有记录
update salesreps set quota=1.05 * quota
//按条件更新表记录
update salesreps set quota=1.08 * quota where area='china'
//按子查询更新表记录
update customers set cust_rep=105
where cust_rep in (
selct empl_num from salesreps where sales < (0.8 * quota)
)
-----------------------------------------------------------
3.3删除数据Delete
语法1:delete from [where ...]
代码:
//所有删除记录
delete from orders
语法2:truncate table
代码2:
//所有删除记录
truncate table orders
//按条件删除记录
delete from orders where order_date < '01/01/2000'
/**********************************************************/
4.数据定义DATA DEFINE LANGUAGE
4.1表Table
4.2列Column
4.3序列Indentity
4.4约束Constraints
4.5索引Index
4.6视图view
4.7权限Privilege
/**********************************************************/
4.1表Table
4.1.1.建立表
语法:
create table (
[长度]
)
代码:
//建立公司部门表
create table tb_basic_dept(
id int not null,
name varchar(20) ,
chair varchar(20)
)
4.1.2.删除表
语法:
drop table
代码:
//删除部门表
drop table tb_basic_dept
-----------------------------------------------------------
4.2列Column
4.2.1.列添加
语法:
alter table add
[长度]
代码:
alter table tb_basic_dept add
remark varchar(50)
4.2.2.列删除
语法:alter table drop column
代码:
alter table tb_basic_dept drop column remark
4.2.3.列修改
语法:alter table alter column
[长度] [null | not null]
代码:
//修改工资列为dec(8,2)
alter table tb_hr_gz alter column gz dec(8,2) null
-----------------------------------------------------------
4.3序列Identity
//特别要求
IDENTITY字段数据类型只能是(int, bigint, smallint, tinyint, decimal, or numeric(x,0))
IDENTITY字段必须是not null约束
4.3.1Identity
语法:
IDENTITY( [, , ]) AS column_name,
代码:
//使用Identity
CREATE TABLE MyTable (
key_col int NOT NULL IDENTITY (1,1),
abc char(1) NOT NULL
)
INSERT INTO MyTable VALUES ('a')
INSERT INTO MyTable VALUES ('b')
INSERT INTO MyTable VALUES ('c')
-----------------------------------------------------------
4.4约束Constraints
4.4.1缺省约束(default)
4.4.2非空约束(not null)
4.4.3规则约束(rule)
4.4.4检查约束(check)
4.4.5唯一约束(unique)
4.4.6主键约束(primary key)
4.4.7外键约束(foreign key)
4.4.8商业规则(business rule)
以下面两个表为例进行演示
create table tb_hr_bm(
bm varchar(20) not null ,
remark varchar(100) default ''
)
create table tb_hr_gz(
id int not null,
name varchar(30) not null,
hrid char(18) null,
workage int null ,
bm varchar(20) null,
gz real null,
remark varchar(100) null
)
hrid=身份证号码
workage=工作年数
gz=工资金额
-----------------------------------------------------------
4.4.1缺省约束(default)
语法:CREATE DEFAULT default_name AS expression
代码:CREATE DEFAULT zip_default AS 94710
-----------------------------------------------------------
4.4.2非空约束(not null)
//表的主键和其它必填字段必须为not null.
语法:create table (column-name datatype not null... )
代码:create table tb_hr_gz(id int not null,...)
-----------------------------------------------------------
4.4.3规则约束(rule)
语法:CREATE RULE rulename AS condition
代码:
//邮编号码6位100000-999999
//建立一个自定义zip类型
CREATE TYPE zip FROM CHAR(6) NOT NULL
//建立一个规则约束
CREATE RULE zip_rule AS @number >100000 and @number < 999999
//绑定规则约束到zip类型
EXEC sp_bindrule zip_rule, 'zip'
//应用自定义zip类型
2> CREATE TABLE address(
city CHAR(25) NOT NULL,
zip_code ZIP,
street CHAR(30) NULL
)
-----------------------------------------------------------
4.4.4检查约束(建立/删除)
//检查约束建立
语法:
alter table name
add constraint check
代码:
//工资添加取值范围0 ~ 1000000
方法1:
create table tb_hr_gz(
gz real default 0.0 check(gz >=0 and gz =0 and gz @y
print 'x > y' --打印字符串'x > y'
else if @y > @z
print 'y > z'
else print 'z > y'
6.2.3.2 CASE语句
--CASE
代码如下:
use pangu
update employee
set e_wage =
case
when job_level = '1' then e_wage*1.08
when job_level = '2' then e_wage*1.07
when job_level = '3' then e_wage*1.06
else
e_wage*1.05
end
6.2.4循环语句(while)
--WHILE
代码如下:
declare @x int @y int @c int
select @x = 1 @y=1
while @x < 3
begin
print @x --打印变量x 的值
while @y < 3
begin
select @c = 100*@x + @y
print @c --打印变量c 的值
select @y = @y + 1
end
select @x = @x + 1
select @y = 1
end
6.2.5定时执行(waitfor)
--WAITFOR
--例 等待1 小时2 分零3 秒后才执行SELECT 语句
waitfor delay '01:02:03'
select * from employee
--例 等到晚上11 点零8 分后才执行SELECT 语句
waitfor time '23:08:00'
select * from employee
-----------------------------------------------------------
6.3脚本游标Cursor
//游标应用顺序
1.DECLARE --为查询设定游标
2.OPEN --检索查询结果打开一个游标
3.FETCH --检索一行查询结果
4.CLOSE / DEALLOCATE--关闭游标或者重新分配游标
语法:
DECLARE CURSOR FOR(select sql)
OPEN
while @@fetch_status = 0
begin
FETCH NEXT FROM INTO
{其它代码处理}
end
CLOSE
代码1:
代码如下:
/*带游标的存储过程*/
create procedure p_fill_remark_tb_hr_gz
as
declare @id1 int
declare @name1 varchar(30)
declare @bm1 varchar(20)
begin
declare cursor1 cursor for select id,name,bm from tb_hr_gz
open cursor1
fetch next from cursor1 into @id1,@name1,@bm1
while @@fetch_status 0
begin
update tb_hr_gz set remark=@name1+'-'+@bm1 where id=@id1
fetch next from cursor1 into @id1,@name1,@bm1
end
close cursor1
end
//测试带游标的存储过程
EXEC dbo.p_fill_remark_tb_hr_gz
-----------------------------------------------------------
6.4存储过程Procedure
//存储过程建立
语法:
create procedure (
[输入参数列表],[返回参数列表 output]
)
as
[局部变量定义]
begin
{语句体}
end
代码:
create procedure p_update_name_tb_hr_gz(@id int,@newname varchar(30))
as
begin
if (exists(select * from tb_hr_gz where id=@id))
begin
update tb_hr_gz set name=@newname where id=@id
end
end
//测试
EXEC dbo.p_update_name_tb_hr_gz '112','chenglei'
//存储过程删除
语法:
drop procedure
代码:
drop procedure p_update_name_tb_hr_gz
-----------------------------------------------------------
6.5存储函数Function
//存储函数建立
语法:
CREATE FUNCTION (参数变量列表)
[返回值RETURNS 数据类型] [WITH ENCRYPTION]
AS
BEGIN
{函数代码体....}
END
代码:
代码如下:
//函数f_amt_to_eng()功能:数字金额转换为英文字母金额
CREATE FUNCTION f_amt_to_eng(@num numeric(15,2))
RETURNS varchar(400) WITH ENCRYPTION
AS
BEGIN
DECLARE @i int,@hundreds int,@tenth int,@one int
DECLARE @thousand int,@million int,@billion int
DECLARE @numbers varchar(400),@s varchar(15),@result varchar(400)
SET @numbers='one two three four five '
+'six seven eight nine ten '
+'eleven twelve thirteen fourteen fifteen '
+'sixteen seventeen eighteen nineteen '
+'twenty thirty forty fifty '
+'sixty seventy eighty ninety '
SET @s=RIGHT('000000000000000'+CAST(@num AS varchar(15)),15)
SET @billion=CAST(SUBSTRING(@s,1,3) AS int)--将12位整数分成4段:十亿、百万、千、百十个
SET @million=CAST(SUBSTRING(@s,4,3) AS int)
SET @thousand=CAST(SUBSTRING(@s,7,3) AS int)
SET @result=''
SET @i=0
WHILE @i0 or @thousand>0 or @hundreds>0)) or
(@i=2 and (@billion>0 or @million>0) and (@thousand>0 or @hundreds>0)) or
(@i=3 and (@billion>0 or @million>0 or @thousand>0) and (@hundreds>0))
SET @result=@result+', '--百位不是0则每段之间加连接符,
IF (@i=3 and (@billion>0 or @million>0 or @thousand>0) and (@hundreds=0 and (@tenth>0 or @one>0)))
SET @result=@result+' and '--百位是0则加连接符AND
IF @hundreds>0
SET @result=@result+RTRIM(SUBSTRING(@numbers,@hundreds*10-9,10))+' hundred'
IF @tenth>=2 and @tenth0
SET @result=@result+' and '
SET @result=@result+RTRIM(SUBSTRING(@numbers,@tenth*10+171,10))
END
IF @one>=1 and @one0
SET @result=@result+'-'
ELSE
IF @hundreds>0
SET @result=@result+' and '
SET @result=@result+RTRIM(SUBSTRING(@numbers,@one*10-9,10))
END
IF @i=0 and @billion>0
SET @result=@result+' billion'
IF @i=1 and @million>0
SET @result=@result+' million'
IF @i=2 and @thousand>0
SET @result=@result+' thousand'
SET @i=@i+1
END
IF SUBSTRING(@s,14,2)'00'
BEGIN
SET @result=@result+' AND '
IF SUBSTRING(@s,14,1)='0'
SET @result=@result+'zero'
ELSE
SET @result=@result+RTRIM(SUBSTRING(@numbers,CAST(SUBSTRING(@s,14,1) AS int)*10-9,10))
IF SUBSTRING(@s,15,1)'0'
SET @result=@result+' '+RTRIM(SUBSTRING(@numbers,CAST(SUBSTRING(@s,15,1) AS int)*10-9,10))
END
RETURN(@result)
END
代码如下:
CREATE FUNCTION f_amt_to_chn (@num numeric(14,2))
RETURNS varchar(100) WITH ENCRYPTION
AS
BEGIN
DECLARE @n_data VARCHAR(20),@c_data VARCHAR(100),@n_str VARCHAR(10),@i int
SET @n_data=RIGHT(SPACE(14)+CAST(CAST(ABS(@num*100) AS bigint) AS varchar(20)),14)
SET @c_data=''
SET @i=1
WHILE @i