SQL MSSQL 常用代码大全
程序员文章站
2023-12-15 19:06:46
/*********************************************************/ function:sql mssql technol...
/*********************************************************/
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 <keyword> <devicename> <devicepath>
代码:
//添加备份设备为本地硬盘
sp_addumpdevice 'disk', 'localbackup', 'e:\database\backup\localbak.bak'
//备份到网络硬盘
sp_addumpdevice 'disk', 'netbackup', '\\computer1\database\backup\netbak.bak'
//备份到磁带
sp_addumpdevice 'tape', 'tapebackup', '\\.\tape1bak'
//备份到命名管道
sp_addumpdevice 'pipe', 'pipebackup', 'e:\database\backup\pipebak'
1.2.2.备份数据库
语法:backup database <databasename> to <devicename>| disk=<backupnamepath>
代码:
//备份数据库到备份设备
backup database pubs to localbackup
//备份数据库到指定路径下面的指定文件
backup database pubs to disk='e:\database\backup\pubsbak.bak'
1.2.3.恢复数据库
语法:restore database <databasename> from <devicename>| disk=<backupnamepath>
代码:
//从备份设备中恢复数据库
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...] [<columnlist as alias...] [const/sql/function expression]
from (<tablelist,>...) [as alias]
[where search expression...]
[group by groupnamelist ....]
[having search-expression...]
[order by sort-expression...]
//select选项说明:
top n:只显示第一条到n条记录
//重复与不重复记录
all:表示包含重复的记录
distinct:表示去掉重复的记录
//所有字段与选中字段和字段别名
*:表示所有的列名
columnlist:表示字段列表
columnlist as alias:表示字段的别名
//其它字段
const-expression:常量表达式(如数字/字符串/日期/时间常量)
sql-expression:常见的sql语句的加减乘除表达式运算字段
function expression:数据库函数和自定义函数字段
//测试条件
比较测试条件(=,<>,>,<,>=,<=)
范围测试条件(betweeen 下限值 and 上限值)
成员测试条件(in,not in)
存在测试条件(exists,not exists)
匹配测试条件(like)
限定测试条件(any,all)
空值测试条件(is null)
//复合搜索条件(and, or,not,())
and:逻辑与运算
and:逻辑或运算
not:逻辑非运算
():可改变优先级的运算符
//子句说明
select子句:指出检索的数据项
from 子句:指出检索的数据表
where 子句:指出检索的数据条件
group by子句:指出检索的数据进行汇总
having子句:指出检索的数据进行汇总之前的条件
order by子句:指出检索的数据条件进行排序
代码:
//所有字段方式显示orders全部记录
select * from orders
//按字段显示全部记录
select order_num,order_date,amount from orders
//按字段显示全部记录,但除掉重复的记录
select order_num,order_date,amount from orders
//用sql-expression乘运算计算列
select amount,amount*0.08 as discount_amt from orders
//用自定义函数计算指定列
select order_num,order_date,amount,f_amt_to_chn(amount) as 金额 from orders
select选项太多,代码例子就省略...
-----------------------------------------------------------
2.2子查询 sub query
语法:select ...
from <tablename>
where / having column 测试条件 (sub query)
//测试条件
比较测试条件(=,<>,>,<,>=,<=)
范围测试条件(betweeen 下限值 and 上限值)
成员测试条件(in,not in)
存在测试条件(exists,not exists)
匹配测试条件(like)
限定测试条件(any,all)
空值测试条件(is null)
代码:
//列出没有完成销售目标10%的销售人员清单[<测试]
select name from salesreps where quota < (0.1 * select sum(target) from offices))
//列出公司的销售目标超过各个销售人员定额总和的销售点[>测试]
select city from offices where target > (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 <tablename>
group by <column-name >
[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 <tablename>[<columnlist,>...] values(<valuelist,>...);
代码:
//不省略字段清单
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 <tablename>[(<columnlist,>...)] values(<valuelist,>...) <select query>;
代码:
//把一批数据批量插入到一个备份表中
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 <tablename> 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 <tablename> [where ...]
代码:
//所有删除记录
delete from orders
语法2:truncate table <tablename>
代码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(<data_type> [, <seed>, <increment>]) 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 <=1000000),
...
)
方法2:
alter table tb_hr_gz
add constraint tb_hr_gz_ck check(gz >=0 and gz <=1000000)
//检查约束删除
语法:
alter table name drop constraint <检查约束名>
代码:
//删除工资的检查约束
alter table tb_hr_gz drop constraint tb_hr_gz_ck
-----------------------------------------------------------
4.4.5唯一约束
4.4.5.1.唯一约束添加
语法:
alter table name add constraint <唯一约束名> unique<列名>
代码:
//列如身份证号码是唯一的!
alter table tb_hr_gz add constraint tb_hr_gz_uk unique(hrid)
4.4.5.2.唯一约束删除
语法:
alter table name drop constraint <唯一约束名>
代码:
alter table tb_hr_gz drop constraint tb_hr_gz_uk
-----------------------------------------------------------
4.4.6主键约束
4.4.6.1主键约束添加
语法:
alter table table_name
add constraint <主键名称> primary key <列名>
代码:
create table tb_hr_bm(
bm varchar(20) not null ,
remark varchar(100) default ''
)
alter table tb_hr_bm
add constraint tb_hr_bm_pk primary key (bm)
4.4.6.2主键约束删除
语法:
alter table table_name
drop constraint <主键名称>
代码:
alter table table_name
drop constraint tb_hr_bm_pk
-----------------------------------------------------------
4.4.7外键约束
4.4.7.1外键约束添加
语法:
alter table <表名>
add constraint <外键名>
foreign key(列名)
references <参考表名><列名>
<on update|on delete(restrict|cascade|set null|set default)>
//补充说明
常用选项是下面3项:
on update set null //级联更新
on delete cascade //级联删除
on delete set null //级联置空
on update(restrict|cascade|set null|set default) 表示父表更新后,子表的行为
on delete(restrict|cascade|set null|set default) 表示父表删除后,子表的行为
restrict 限制功能:父表一行记录不能更新/删除,当子表有一条记录以上时
cascade 级联功能:父表一行记录记录更新/删除删除,子表对应所有的记录自动更新/删除
set null 置空功能:父表一行记录记录更新/删除删除,子表对应所有的记录自动为空
set default 默认值功能:父表一行记录记录更新/删除删除,子表对应所有的记录自动写入默认值
代码:
建立外键的主要代码
alter table tb_hr_personl_info
add constraint tb_hr_personl_info__bm_fk
foreign key(bm)
references tb_hr_bm (bm)
on update cascade
on delete cascade
//建立参考表部门
create table tb_hr_bm
(
bm varchar(20) not null ,
remark varchar(100) default ''
)
alter table tb_hr_bm
add constraint tb_hr_bm_pk primary key (bm)
//建立个人信息表
use hr
create table tb_hr_personl_info
(
userid int not null ,
username varchar(20) null,
bm varchar(20) null
)
/*为此表添加主键约束*/
alter table tb_hr_personl_info
add constraint tb_hr_personl_info_pk primary key (userid)
/*为个人信息表添加外键约束*/
alter table tb_hr_personl_info
add constraint tb_hr_personl_info__bm_fk
foreign key(bm)
references tb_hr_bm (bm)
on update cascade
on delete cascade
-----------------------------------------------------------
4.4.7.2外键约束删除
语法:
alter table <表名>
drop constraint <外键名>
代码:
//删除tb_hr_personl_info表的外键
alter table tb_hr_personl_info drop constraint tb_hr_personl_info__bm_fk;
-----------------------------------------------------------
4.4.8商业规则(business rule)
//用触发器或者存储过程来实现
-----------------------------------------------------------
4.5索引index
//4.5.1建立索引
语法:
create index <索引名>
on <表名> <列名清表>
代码:
create index tb_hr_personl_info_ix
on tb_hr_personl_info (userid)
//4.5.2删除索引
语法:
drop index <表名><.><索引名>
代码:
//删除索引名tb_hr_personl_info_ix
drop index tb_hr_personl_info.tb_hr_personl_info_ix
-----------------------------------------------------------
4.6视图view
4.6.1视图view的概念:
视图不是表,也不是表数据的备份,在数据库模式中只是select语句的集合!
-----------------------------------------------------------
4.6.2建立视图create view
语法:
create view <view name>
as
<select statement>
with check option
代码:
create view vw_customerlist
as
select *
from customers
-----------------------------------------------------------
4.6.3查询视图query view
语法:select * from viewname
代码:select * from vw_customerlist
-----------------------------------------------------------
4.6.4修改视图alter view
语法:select * from viewname
代码:select * from vw_customerlist
-----------------------------------------------------------
4.6.5视图删除drop view
//4.6.2视图删除
语法:
drop view <视图名>
代码:
//视图删除v_hr_personl_info
drop view v_hr_personl_info
-----------------------------------------------------------
4.6.6.过滤视图filter view
语法:
select * from viewname where/having expressions
代码:
create view bankersmin
as
select bankername, bankerstate
from bankers
where bankerid < 5
select * from bankersmin
where bankerstate = 'ca'
order by bankername
-----------------------------------------------------------
4.6.7.可更新的视图updatable view
语法:
create view <view name>
as
select statement
with check option
代码:
create view oregonshippers_vw
as
select shipperid,
companyname,
phone
from shippers
with check option
//此视图的记录可以进行delete/update/insert
insert into <view name> values(values....)
delete from <view name> where/having expressions
update <view name> set column =values... where/having expressions
-----------------------------------------------------------
4.7权限privilege
4.7.1数据库用户添加
语法:
sp_addlogin [ @loginame = ] 'login'
[ , [ @passwd = ] 'password' ]
[ , [ @defdb = ] 'database' ]
[ , [ @deflanguage = ] 'language' ]
[ , [ @sid = ] sid ]
[ , [ @encryptopt= ] 'encryption_option' ]
代码:
数据库testdb上面添加一个登陆用户test,密码为tt
exec sp_addlogin 'test', 'tt', 'testdb', 'us_english'
exec sp_addlogin 'yao', 'it', 'mtyjxc', 'us_english'
-----------------------------------------------------------
4.7.2数据库用户删除
语法:drop login <登陆名称>
代码:drop login test
-----------------------------------------------------------
4.7.3用户权限授予grant
grant语法:
grant privilege [, ...] on object [, ...]
to { public | group group | username }
privilege取值范围如下:
select:访问声明的表/视图的所有列/字段.
insert:向声明的表中插入所有列字段.
update:更新声明的表所有列/字段.
delete:从声明的表中删除所有行.
rule:在表/视图上定义规则 (参见 create rule 语句).
all:赋予所有权限.
object取值范围如下:
table
view
sequence
public:代表是所有用户的简写.
group:将要赋予权限的组 group
username:将要赋予权限的用户名.
如果成功,返回输出change信息.
代码:
grant all on mtyjxc to 'yao'
-----------------------------------------------------------
7.7.4用户权限解除revoke
revoke { all | statement [ ,...n ] }
from security_account [ ,...n ]
all:
指定将删除所有适用的权限。
对于语句权限,只有 sysadmin 固定服务器角色成员可以使用 all。
对于对象权限,sysadmin 固定服务器角色成员、db_owne 固定数据库角色成员和数据库对象所有者都可以使用 all。
statement:
是要删除其权限的授权语句。语句列表可以包括:
* create database
* create default
* create function
* create procedure
* create rule
* create table
* create view
* backup database
* backup log
from:
指定安全帐户列表。
security_account:
是当前数据库内将要被删除权限的安全帐户。
安全帐户可以是:sql server用户,sql server角色。
代码:
revoke all on mtyjxc.* to yao
revoke all on mtyjxc to yao
/**********************************************************/
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
-----------------------------------------------------------
5.1转换函数data convert functions
5.1.1 cast()
功能:数据类型转换
语法:cast(expression as data_type)
代码:
select billingdate,
billingtotal,
cast(billingdate as varchar) as varchardate,
cast(billingtotal as int) as integertotal,
cast(billingtotal as varchar) as varchartotal
from billings
-----------------------------------------------------------
5.1.2 coalesce()
功能:返回表达式列表中第一个非空值表达式的值
语法:coalesce(expression1, expression2, ... expressionn)
代码:
select bankername,
coalesce(cast(billingtotal as varchar), 'no billings') as billingtotal
from bankers left join billings
on bankers.bankerid = billings.bankerid
order by bankername
-----------------------------------------------------------
5.1.3 convert()
功能:把表达式值转换为指定sytle的数据类型
语法:convert(data_ type(<length>), expression, <style>)
代码:
//日期风格转换
datetime转指定日期格式style number清单
number style number output type style
- 0 or 100 default mon dd yyyy hh:miam (or pm)
1 101 usa mm/dd/yyyy
2 102 ansi yyyy.mm.dd
3 103 british/french dd/mm/yyyy
4 104 german dd.mm.yyyy
5 105 italian dd-mm-yyyy
6 106 - dd mon yyyy
7 107 - mon dd, yyyy
10 110 usa mm-dd-yy
11 111 japan yy/mm/dd
12 112 iso yymmdd
14 114 - hh:mi:ss:mmm (24h)
//字符串转数字
convert (integer , '12345')
//字符转日期
convert(datetime, '20000704')
create table my_date (col1 datetime)
go
insert into my_date values (convert(char(10), getdate(), 112))
go
drop table my_date;
go
-----------------------------------------------------------
5.1.4 isnull()
功能:检查check_expression是空值,就用replacement_value替代
语法:isnull(check_expression, replacement_value)
代码:
select billingdate,
isnull(billingdate, '1900-01-01') as newdate
from billings
-----------------------------------------------------------
5.1.5 nullif()
功能:两个表达式相等,返回null,否则返回第1个表达式
语法:isnull(expression1, expression2)
代码:
declare @value1 int
declare @value2 int
set @value1 = 55
set @value2 = 955
select nullif(@value1, @value2)
go
输出
55
declare @value1 int
declare @value2 int
set @value1 = 55
set @value2 = 55
select nullif(@value1, @value2)
go
输出
null
-----------------------------------------------------------
5.2聚集函数aggregate functions
语法:select aggregatefunctions(column-name)
sum(column-name):计算字段总和
avg(column-name):计算字段平均值
min(column-name):计算字段最小值
max(column-name):计算字段最大值
count(column-name):计算字段非空值的个数
count(*):计算查询结果的记录个数
代码:
//use pubs
select sum(qty) as sum_qty,
avg(qty) as avg_qty,
min(qty) as min_qty,
max(qty) as max_qty,
count(qty) as count_qty,
count(*) as total_qty
from sales
-----------------------------------------------------------
5.3字符函数char functions
1. ascii()
//函数返回字符表达式最左端字符的ascii 码值
2. char()
//函数用于将ascii 码转换为字符--如果没有输入0 ~ 255 之间的ascii 码值char 函数会返回一个null
3. charindex()
//函数返回字符串中某个指定的子串出现的开始位置
4. difference()
5. formatmessage()
6. left()
7. len()
8. lower()
//函数把字符串全部转换为小写
9. ltrim()
//函数把字符串头部的空格去掉
10.nchar()
11.patindex()
12.quotename()
13.replace()
//函数返回被替换了指定子串的字符串
14.replicate()
/函数返回一个重复指定次数的字符串
15.reverse()
//函数将指定的字符串的字符排列顺序颠倒
16.right()
17.rtrim()
/函数把字符串尾部的空格去掉
18.soundex()
19.space()
//函数返回一个有指定长度的空白字符串
20.str()
//函数把数值型数据转换为字符型数据
21.stuff()
//函数用另一子串替换字符串指定位置长度的子串
22.substring()
//函数返回子字符串
23.unicode()
24.upper()
//函数把字符串全部转换为大写
-----------------------------------------------------------
5.4日期函数date functions
5.4.1. current_timestamp
功能:
得到当前数据库的日期
代码:
//直接得到当前日期
select current_timestamp
go
//调用变量中的当前日期
declare @today datetime
select @today = current_timestamp
select @today
go
-----------------------------------------------------------
5.4.2. 日期计算date calculation
功能:日期计算
代码:
declare @monthchar varchar(2), @daychar varchar(2), @dateout char(8)
set @monthchar = cast(month(getdate()) as varchar(2))
set @daychar = cast(day(getdate()) as varchar(2))
--自动补齐月份到2位
if len(@monthchar) = 1
set @monthchar = '0'+@monthchar
if len(@daychar) = 1
set @daychar = '0' + @daychar
--生成日期字符串
set @dateout = @monthchar + @daychar + cast(year(getdate()) as char(4))
select @dateout
go
运行结果是mmddyyyy格式的字符串
-----------------------------------------------------------
5.4.3. dateadd()
功能:日期相加或者相减n天后的日期
语法:dateadd(what_to_add,number_to_add,date_to_add_it_to)
代码:
//4-29-2009加90天,保存到day
select dateadd(dy, 90,'4-29-2009')
go
//4-29-2009减60天,保存到day
select dateadd(dy, -60,'4-29-2009')
go
-----------------------------------------------------------
5.4.4. datediff()
功能:日期相加或者相减n天后的日期
语法:datediff ( datepart , startdate , enddate )
datepart列表:
day:单位=天
month:单位=月
year:单位=年
hour:单位=小时
minute:单位=分
second:单位=秒
week:单位=周
代码:
//10/01/2009国庆到今天的天数
select datediff(day,'10/1/2009',current_timestamp)
go
//10/01/2009国庆到今天的月数
select datediff(month,'10/1/2009',current_timestamp)
go
//10/01/2009国庆到今天的年数
select datediff(year,'10/1/2009',current_timestamp)
go
//10/01/2009国庆到今天的周数
select datediff(week,'10/1/2009',current_timestamp)
go
-----------------------------------------------------------
5.4.5. datefirst()
功能:设置或者查询一周的第一天
select @@datefirst 'first day of the week'
go
value is 7
select datepart(weekday, cast('20091001' as datetime) + @@datefirst);
go
value is 3
-----------------------------------------------------------
6. dateformat()
功能:设置日期格式
语法:set dateformat <format>
format(ymd,mdy,dmy)
代码:set dataformat mdy
-----------------------------------------------------------
7. datename()
功能:日期date按datepart风格之后变成字符串
语法:datename (datepart,date)
datepart列表(day,month,year,hour,minute,second,week,weekday)
代码:
select datename(day,current_timestamp)
select datename(month,current_timestamp)
select datename(year,current_timestamp)
select datename(hour,current_timestamp)
select datename(minute,current_timestamp)
select datename(week,current_timestamp)
select datename(weekday,current_timestamp)
-----------------------------------------------------------
8. datepart()
功能:日期date按datepart风格之后变成字符串
语法:datename (datepart,date)
datepart列表(day,month,year,hour,minute,second,week,weekday)
代码:
-----------------------------------------------------------
9. day()
功能:求日期的天
语法:day(date)
代码:select day(current_timestamp)
-----------------------------------------------------------
10. getdate()
功能:求当前日期和时间
语法:getdate()
代码:select getdate() 和select current_timestamp相同
-----------------------------------------------------------
11. getutcdate()
-----------------------------------------------------------
12. isdate()
-----------------------------------------------------------
13. month()
功能:求日期的月
语法:month(date)
代码:select month(current_timestamp)
-----------------------------------------------------------
14. year()
功能:求日期的年
语法:year(date)
代码:select year(current_timestamp)
-----------------------------------------------------------
5.5数学函数math functions
1. abs()
2. acos()
3. asin()
4. atan()
5. ceiling()
6. cos()
7. cot()
8. degrees()
9. exp()
10. floor()
11. isnumeric()
12. log()
13. log10()
14. pi()
15. power()
16. radians()
11. 17. rand()
18. round()
19. sign()
20. sin()
21. sqrt()
22. square()
23. tan()
-----------------------------------------------------------
5.6分析函数analytical functions
1. compute()
2. cube()
3. dense_rank()
4. grouping()
5. ntile()
6. partition()
7. pivot()
8. rollup()
9. row_number()
10. stdev()
11. stdevp()
12. var()
13. varp()
/**********************************************************/
6.transact sql
6.1数据类型data types
6.2脚本语法sytanx
6.3脚本游标cursor
6.4存储过程procedure
6.5存储函数function
6.6触发器trigger
6.7事务transaction
6.8其它other
/**********************************************************/
6.1数据类型data types
1. bigint
2. bit
3. bitwise operators
4. char
5. collate
6. create type
7. data type
8. date type
9. datetime
10. decimal
11. float
12. fulltext
13. integer
14. large text
15. money
16. nchar
17. nvarchar
18. openrowset
19. readtext
20. smalldatetime
21. smallint
22. sql_variant
23. text
24. textptr
25. timestamp
26. varbinary
27. varchar
28. writetext
29. unicode
-----------------------------------------------------------
6.2脚本语法syntax
6.2.0局部/全局变量定义
局部变量 (以@开头)
格式:declare @变量名 数据类型
代码:declare @x int
全局变量 (必须以@@开头)
格式:declare @@变量名 类型
代码:select @@id = '10010001'
6.2.1块语句
格式:
begin
...
end
-----------------------------------------------------------
6.2.2赋值语句set/select
set @id = '10010001'
select @id = '10010001'
6.2.3条件语句(if/case)
6.2.3.1 if语句
declare @x int @y int @z int
select @x = 1 @y = 2 @z=3
if @x > @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 @i<=3
begin
set @hundreds=cast(substring(@s,@i*3+1,1) as int)--百位0-9
set @tenth=cast(substring(@s,@i*3+2,1) as int)
set @one=(case @tenth when 1 then 10 else 0 end)+cast(substring(@s,@i*3+3,1) as int)--个位0-19
set @tenth=(case when @tenth<=1 then 0 else @tenth end)--十位0、2-9
if (@i=1 and @billion>0 and (@million>0 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 @tenth<=9
begin
if @hundreds>0
set @result=@result+' and '
set @result=@result+rtrim(substring(@numbers,@tenth*10+171,10))
end
if @one>=1 and @one<=19
begin
if @tenth>0
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<=14
begin
set @n_str=substring(@n_data,@i,1)
if @n_str<>' '
begin
if not ((substring(@n_data,@i,2)='00') or ((@n_str='0') and ((@i=4) or (@i=8) or (@i=12) or (@i=14))))
set @c_data=@c_data+substring('零壹贰叁肆伍陆柒捌玖',cast(@n_str as int)+1,1)
if not ((@n_str='0') and (@i<>4) and (@i<>8) and (@i<>12))
set @c_data=@c_data+substring('仟佰拾亿仟佰拾万仟佰拾元角分',@i,1)
if substring(@c_data,len(@c_data)-1,2)='亿万'
set @c_data=substring(@c_data,1,len(@c_data)-1)
end
set @i=@i+1
end
if @num<0
set @c_data='负'+@c_data
if @num=0
set @c_data='零元'
if @n_str='0'
set @c_data=@c_data+'整'
return(@c_data)
end
//测试函数
select name, gz,dbo.f_amt_to_chn(gz) as 中文金额,dbo.f_amt_to_eng(gz) as 英文金额 from tb_hr_gz
//删除函数
语法:
drop function <函数名称>
代码:
drop function f_num_to_eng
-----------------------------------------------------------
6.6触发器trigger
22. 1. trigger( 14 ) 22. 10. trigger order( 2 )
22. 2. alter trigger( 4 ) 22. 11. drop trigger( 2 )
22. 3. trigger for after( 4 ) 22. 12. columns_updated( 1 )
22. 4. trigger for delete( 4 ) 22. 13. update function( 3 )
22. 5. trigger for insert( 1 ) 22. 14. deleted table( 2 )
22. 6. trigger for update( 4 ) 22. 15. inserted table( 5 )
22. 7. trigger on database( 2 ) 22. 16. recursive_triggers( 1 )
22. 8. trigger on server( 1 ) 22. 17. utility trigger( 4 )
22. 9. trigger on view( 3 )
//触发器建立
语法:
create trigger <触发器名称> on <表名>
[for insert | update | delete]
as
[定义变量]
begin
{代码块...}
end
代码0:
create trigger tg_tb_hr_bm on tb_hr_bm
for insert,update,delete
as
declare @bm_d varchar(20)
declare @bm_i varchar(20)
begin
set @bm_d=(select bm from deleted)
set @bm_i=(select bm from inserted)
if exists(select * from tb_hr_gz ,deleted where(tb_hr_gz.bm =deleted.bm ))
begin
update tb_hr_gz set bm='' where bm =@bm_d
end
if update(bm)
begin
update tb_hr_gz set bm=@bm_i where bm =@bm_i
end
end
//删除触发器
语法:
drop trigger <触发器名称>
代码:
drop trigger tg_w_house_center
-----------------------------------------------------------
6.7事务transaction
事务(commit/rollback)
set transaction --定义当前事务数据访问特征
commit --提交当前事务
rollback --取消当前事务
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 <keyword> <devicename> <devicepath>
代码:
//添加备份设备为本地硬盘
sp_addumpdevice 'disk', 'localbackup', 'e:\database\backup\localbak.bak'
//备份到网络硬盘
sp_addumpdevice 'disk', 'netbackup', '\\computer1\database\backup\netbak.bak'
//备份到磁带
sp_addumpdevice 'tape', 'tapebackup', '\\.\tape1bak'
//备份到命名管道
sp_addumpdevice 'pipe', 'pipebackup', 'e:\database\backup\pipebak'
1.2.2.备份数据库
语法:backup database <databasename> to <devicename>| disk=<backupnamepath>
代码:
//备份数据库到备份设备
backup database pubs to localbackup
//备份数据库到指定路径下面的指定文件
backup database pubs to disk='e:\database\backup\pubsbak.bak'
1.2.3.恢复数据库
语法:restore database <databasename> from <devicename>| disk=<backupnamepath>
代码:
//从备份设备中恢复数据库
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...] [<columnlist as alias...] [const/sql/function expression]
from (<tablelist,>...) [as alias]
[where search expression...]
[group by groupnamelist ....]
[having search-expression...]
[order by sort-expression...]
//select选项说明:
top n:只显示第一条到n条记录
//重复与不重复记录
all:表示包含重复的记录
distinct:表示去掉重复的记录
//所有字段与选中字段和字段别名
*:表示所有的列名
columnlist:表示字段列表
columnlist as alias:表示字段的别名
//其它字段
const-expression:常量表达式(如数字/字符串/日期/时间常量)
sql-expression:常见的sql语句的加减乘除表达式运算字段
function expression:数据库函数和自定义函数字段
//测试条件
比较测试条件(=,<>,>,<,>=,<=)
范围测试条件(betweeen 下限值 and 上限值)
成员测试条件(in,not in)
存在测试条件(exists,not exists)
匹配测试条件(like)
限定测试条件(any,all)
空值测试条件(is null)
//复合搜索条件(and, or,not,())
and:逻辑与运算
and:逻辑或运算
not:逻辑非运算
():可改变优先级的运算符
//子句说明
select子句:指出检索的数据项
from 子句:指出检索的数据表
where 子句:指出检索的数据条件
group by子句:指出检索的数据进行汇总
having子句:指出检索的数据进行汇总之前的条件
order by子句:指出检索的数据条件进行排序
代码:
//所有字段方式显示orders全部记录
select * from orders
//按字段显示全部记录
select order_num,order_date,amount from orders
//按字段显示全部记录,但除掉重复的记录
select order_num,order_date,amount from orders
//用sql-expression乘运算计算列
select amount,amount*0.08 as discount_amt from orders
//用自定义函数计算指定列
select order_num,order_date,amount,f_amt_to_chn(amount) as 金额 from orders
select选项太多,代码例子就省略...
-----------------------------------------------------------
2.2子查询 sub query
语法:select ...
from <tablename>
where / having column 测试条件 (sub query)
//测试条件
比较测试条件(=,<>,>,<,>=,<=)
范围测试条件(betweeen 下限值 and 上限值)
成员测试条件(in,not in)
存在测试条件(exists,not exists)
匹配测试条件(like)
限定测试条件(any,all)
空值测试条件(is null)
代码:
//列出没有完成销售目标10%的销售人员清单[<测试]
select name from salesreps where quota < (0.1 * select sum(target) from offices))
//列出公司的销售目标超过各个销售人员定额总和的销售点[>测试]
select city from offices where target > (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 <tablename>
group by <column-name >
[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 <tablename>[<columnlist,>...] values(<valuelist,>...);
代码:
//不省略字段清单
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 <tablename>[(<columnlist,>...)] values(<valuelist,>...) <select query>;
代码:
//把一批数据批量插入到一个备份表中
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 <tablename> 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 <tablename> [where ...]
代码:
//所有删除记录
delete from orders
语法2:truncate table <tablename>
代码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(<data_type> [, <seed>, <increment>]) 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 <=1000000),
...
)
方法2:
alter table tb_hr_gz
add constraint tb_hr_gz_ck check(gz >=0 and gz <=1000000)
//检查约束删除
语法:
alter table name drop constraint <检查约束名>
代码:
//删除工资的检查约束
alter table tb_hr_gz drop constraint tb_hr_gz_ck
-----------------------------------------------------------
4.4.5唯一约束
4.4.5.1.唯一约束添加
语法:
alter table name add constraint <唯一约束名> unique<列名>
代码:
//列如身份证号码是唯一的!
alter table tb_hr_gz add constraint tb_hr_gz_uk unique(hrid)
4.4.5.2.唯一约束删除
语法:
alter table name drop constraint <唯一约束名>
代码:
alter table tb_hr_gz drop constraint tb_hr_gz_uk
-----------------------------------------------------------
4.4.6主键约束
4.4.6.1主键约束添加
语法:
alter table table_name
add constraint <主键名称> primary key <列名>
代码:
create table tb_hr_bm(
bm varchar(20) not null ,
remark varchar(100) default ''
)
alter table tb_hr_bm
add constraint tb_hr_bm_pk primary key (bm)
4.4.6.2主键约束删除
语法:
alter table table_name
drop constraint <主键名称>
代码:
alter table table_name
drop constraint tb_hr_bm_pk
-----------------------------------------------------------
4.4.7外键约束
4.4.7.1外键约束添加
语法:
alter table <表名>
add constraint <外键名>
foreign key(列名)
references <参考表名><列名>
<on update|on delete(restrict|cascade|set null|set default)>
//补充说明
常用选项是下面3项:
on update set null //级联更新
on delete cascade //级联删除
on delete set null //级联置空
on update(restrict|cascade|set null|set default) 表示父表更新后,子表的行为
on delete(restrict|cascade|set null|set default) 表示父表删除后,子表的行为
restrict 限制功能:父表一行记录不能更新/删除,当子表有一条记录以上时
cascade 级联功能:父表一行记录记录更新/删除删除,子表对应所有的记录自动更新/删除
set null 置空功能:父表一行记录记录更新/删除删除,子表对应所有的记录自动为空
set default 默认值功能:父表一行记录记录更新/删除删除,子表对应所有的记录自动写入默认值
代码:
建立外键的主要代码
alter table tb_hr_personl_info
add constraint tb_hr_personl_info__bm_fk
foreign key(bm)
references tb_hr_bm (bm)
on update cascade
on delete cascade
//建立参考表部门
create table tb_hr_bm
(
bm varchar(20) not null ,
remark varchar(100) default ''
)
alter table tb_hr_bm
add constraint tb_hr_bm_pk primary key (bm)
//建立个人信息表
use hr
create table tb_hr_personl_info
(
userid int not null ,
username varchar(20) null,
bm varchar(20) null
)
/*为此表添加主键约束*/
alter table tb_hr_personl_info
add constraint tb_hr_personl_info_pk primary key (userid)
/*为个人信息表添加外键约束*/
alter table tb_hr_personl_info
add constraint tb_hr_personl_info__bm_fk
foreign key(bm)
references tb_hr_bm (bm)
on update cascade
on delete cascade
-----------------------------------------------------------
4.4.7.2外键约束删除
语法:
alter table <表名>
drop constraint <外键名>
代码:
//删除tb_hr_personl_info表的外键
alter table tb_hr_personl_info drop constraint tb_hr_personl_info__bm_fk;
-----------------------------------------------------------
4.4.8商业规则(business rule)
//用触发器或者存储过程来实现
-----------------------------------------------------------
4.5索引index
//4.5.1建立索引
语法:
create index <索引名>
on <表名> <列名清表>
代码:
create index tb_hr_personl_info_ix
on tb_hr_personl_info (userid)
//4.5.2删除索引
语法:
drop index <表名><.><索引名>
代码:
//删除索引名tb_hr_personl_info_ix
drop index tb_hr_personl_info.tb_hr_personl_info_ix
-----------------------------------------------------------
4.6视图view
4.6.1视图view的概念:
视图不是表,也不是表数据的备份,在数据库模式中只是select语句的集合!
-----------------------------------------------------------
4.6.2建立视图create view
语法:
create view <view name>
as
<select statement>
with check option
代码:
create view vw_customerlist
as
select *
from customers
-----------------------------------------------------------
4.6.3查询视图query view
语法:select * from viewname
代码:select * from vw_customerlist
-----------------------------------------------------------
4.6.4修改视图alter view
语法:select * from viewname
代码:select * from vw_customerlist
-----------------------------------------------------------
4.6.5视图删除drop view
//4.6.2视图删除
语法:
drop view <视图名>
代码:
//视图删除v_hr_personl_info
drop view v_hr_personl_info
-----------------------------------------------------------
4.6.6.过滤视图filter view
语法:
select * from viewname where/having expressions
代码:
create view bankersmin
as
select bankername, bankerstate
from bankers
where bankerid < 5
select * from bankersmin
where bankerstate = 'ca'
order by bankername
-----------------------------------------------------------
4.6.7.可更新的视图updatable view
语法:
create view <view name>
as
select statement
with check option
代码:
create view oregonshippers_vw
as
select shipperid,
companyname,
phone
from shippers
with check option
//此视图的记录可以进行delete/update/insert
insert into <view name> values(values....)
delete from <view name> where/having expressions
update <view name> set column =values... where/having expressions
-----------------------------------------------------------
4.7权限privilege
4.7.1数据库用户添加
语法:
sp_addlogin [ @loginame = ] 'login'
[ , [ @passwd = ] 'password' ]
[ , [ @defdb = ] 'database' ]
[ , [ @deflanguage = ] 'language' ]
[ , [ @sid = ] sid ]
[ , [ @encryptopt= ] 'encryption_option' ]
代码:
数据库testdb上面添加一个登陆用户test,密码为tt
exec sp_addlogin 'test', 'tt', 'testdb', 'us_english'
exec sp_addlogin 'yao', 'it', 'mtyjxc', 'us_english'
-----------------------------------------------------------
4.7.2数据库用户删除
语法:drop login <登陆名称>
代码:drop login test
-----------------------------------------------------------
4.7.3用户权限授予grant
grant语法:
grant privilege [, ...] on object [, ...]
to { public | group group | username }
privilege取值范围如下:
select:访问声明的表/视图的所有列/字段.
insert:向声明的表中插入所有列字段.
update:更新声明的表所有列/字段.
delete:从声明的表中删除所有行.
rule:在表/视图上定义规则 (参见 create rule 语句).
all:赋予所有权限.
object取值范围如下:
table
view
sequence
public:代表是所有用户的简写.
group:将要赋予权限的组 group
username:将要赋予权限的用户名.
如果成功,返回输出change信息.
代码:
grant all on mtyjxc to 'yao'
-----------------------------------------------------------
7.7.4用户权限解除revoke
revoke { all | statement [ ,...n ] }
from security_account [ ,...n ]
all:
指定将删除所有适用的权限。
对于语句权限,只有 sysadmin 固定服务器角色成员可以使用 all。
对于对象权限,sysadmin 固定服务器角色成员、db_owne 固定数据库角色成员和数据库对象所有者都可以使用 all。
statement:
是要删除其权限的授权语句。语句列表可以包括:
* create database
* create default
* create function
* create procedure
* create rule
* create table
* create view
* backup database
* backup log
from:
指定安全帐户列表。
security_account:
是当前数据库内将要被删除权限的安全帐户。
安全帐户可以是:sql server用户,sql server角色。
代码:
revoke all on mtyjxc.* to yao
revoke all on mtyjxc to yao
/**********************************************************/
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
-----------------------------------------------------------
5.1转换函数data convert functions
5.1.1 cast()
功能:数据类型转换
语法:cast(expression as data_type)
代码:
select billingdate,
billingtotal,
cast(billingdate as varchar) as varchardate,
cast(billingtotal as int) as integertotal,
cast(billingtotal as varchar) as varchartotal
from billings
-----------------------------------------------------------
5.1.2 coalesce()
功能:返回表达式列表中第一个非空值表达式的值
语法:coalesce(expression1, expression2, ... expressionn)
代码:
select bankername,
coalesce(cast(billingtotal as varchar), 'no billings') as billingtotal
from bankers left join billings
on bankers.bankerid = billings.bankerid
order by bankername
-----------------------------------------------------------
5.1.3 convert()
功能:把表达式值转换为指定sytle的数据类型
语法:convert(data_ type(<length>), expression, <style>)
代码:
//日期风格转换
datetime转指定日期格式style number清单
number style number output type style
- 0 or 100 default mon dd yyyy hh:miam (or pm)
1 101 usa mm/dd/yyyy
2 102 ansi yyyy.mm.dd
3 103 british/french dd/mm/yyyy
4 104 german dd.mm.yyyy
5 105 italian dd-mm-yyyy
6 106 - dd mon yyyy
7 107 - mon dd, yyyy
10 110 usa mm-dd-yy
11 111 japan yy/mm/dd
12 112 iso yymmdd
14 114 - hh:mi:ss:mmm (24h)
//字符串转数字
convert (integer , '12345')
//字符转日期
convert(datetime, '20000704')
create table my_date (col1 datetime)
go
insert into my_date values (convert(char(10), getdate(), 112))
go
drop table my_date;
go
-----------------------------------------------------------
5.1.4 isnull()
功能:检查check_expression是空值,就用replacement_value替代
语法:isnull(check_expression, replacement_value)
代码:
select billingdate,
isnull(billingdate, '1900-01-01') as newdate
from billings
-----------------------------------------------------------
5.1.5 nullif()
功能:两个表达式相等,返回null,否则返回第1个表达式
语法:isnull(expression1, expression2)
代码:
declare @value1 int
declare @value2 int
set @value1 = 55
set @value2 = 955
select nullif(@value1, @value2)
go
输出
55
declare @value1 int
declare @value2 int
set @value1 = 55
set @value2 = 55
select nullif(@value1, @value2)
go
输出
null
-----------------------------------------------------------
5.2聚集函数aggregate functions
语法:select aggregatefunctions(column-name)
sum(column-name):计算字段总和
avg(column-name):计算字段平均值
min(column-name):计算字段最小值
max(column-name):计算字段最大值
count(column-name):计算字段非空值的个数
count(*):计算查询结果的记录个数
代码:
//use pubs
select sum(qty) as sum_qty,
avg(qty) as avg_qty,
min(qty) as min_qty,
max(qty) as max_qty,
count(qty) as count_qty,
count(*) as total_qty
from sales
-----------------------------------------------------------
5.3字符函数char functions
1. ascii()
//函数返回字符表达式最左端字符的ascii 码值
2. char()
//函数用于将ascii 码转换为字符--如果没有输入0 ~ 255 之间的ascii 码值char 函数会返回一个null
3. charindex()
//函数返回字符串中某个指定的子串出现的开始位置
4. difference()
5. formatmessage()
6. left()
7. len()
8. lower()
//函数把字符串全部转换为小写
9. ltrim()
//函数把字符串头部的空格去掉
10.nchar()
11.patindex()
12.quotename()
13.replace()
//函数返回被替换了指定子串的字符串
14.replicate()
/函数返回一个重复指定次数的字符串
15.reverse()
//函数将指定的字符串的字符排列顺序颠倒
16.right()
17.rtrim()
/函数把字符串尾部的空格去掉
18.soundex()
19.space()
//函数返回一个有指定长度的空白字符串
20.str()
//函数把数值型数据转换为字符型数据
21.stuff()
//函数用另一子串替换字符串指定位置长度的子串
22.substring()
//函数返回子字符串
23.unicode()
24.upper()
//函数把字符串全部转换为大写
-----------------------------------------------------------
5.4日期函数date functions
5.4.1. current_timestamp
功能:
得到当前数据库的日期
代码:
//直接得到当前日期
select current_timestamp
go
//调用变量中的当前日期
declare @today datetime
select @today = current_timestamp
select @today
go
-----------------------------------------------------------
5.4.2. 日期计算date calculation
功能:日期计算
代码:
declare @monthchar varchar(2), @daychar varchar(2), @dateout char(8)
set @monthchar = cast(month(getdate()) as varchar(2))
set @daychar = cast(day(getdate()) as varchar(2))
--自动补齐月份到2位
if len(@monthchar) = 1
set @monthchar = '0'+@monthchar
if len(@daychar) = 1
set @daychar = '0' + @daychar
--生成日期字符串
set @dateout = @monthchar + @daychar + cast(year(getdate()) as char(4))
select @dateout
go
运行结果是mmddyyyy格式的字符串
-----------------------------------------------------------
5.4.3. dateadd()
功能:日期相加或者相减n天后的日期
语法:dateadd(what_to_add,number_to_add,date_to_add_it_to)
代码:
//4-29-2009加90天,保存到day
select dateadd(dy, 90,'4-29-2009')
go
//4-29-2009减60天,保存到day
select dateadd(dy, -60,'4-29-2009')
go
-----------------------------------------------------------
5.4.4. datediff()
功能:日期相加或者相减n天后的日期
语法:datediff ( datepart , startdate , enddate )
datepart列表:
day:单位=天
month:单位=月
year:单位=年
hour:单位=小时
minute:单位=分
second:单位=秒
week:单位=周
代码:
//10/01/2009国庆到今天的天数
select datediff(day,'10/1/2009',current_timestamp)
go
//10/01/2009国庆到今天的月数
select datediff(month,'10/1/2009',current_timestamp)
go
//10/01/2009国庆到今天的年数
select datediff(year,'10/1/2009',current_timestamp)
go
//10/01/2009国庆到今天的周数
select datediff(week,'10/1/2009',current_timestamp)
go
-----------------------------------------------------------
5.4.5. datefirst()
功能:设置或者查询一周的第一天
select @@datefirst 'first day of the week'
go
value is 7
select datepart(weekday, cast('20091001' as datetime) + @@datefirst);
go
value is 3
-----------------------------------------------------------
6. dateformat()
功能:设置日期格式
语法:set dateformat <format>
format(ymd,mdy,dmy)
代码:set dataformat mdy
-----------------------------------------------------------
7. datename()
功能:日期date按datepart风格之后变成字符串
语法:datename (datepart,date)
datepart列表(day,month,year,hour,minute,second,week,weekday)
代码:
select datename(day,current_timestamp)
select datename(month,current_timestamp)
select datename(year,current_timestamp)
select datename(hour,current_timestamp)
select datename(minute,current_timestamp)
select datename(week,current_timestamp)
select datename(weekday,current_timestamp)
-----------------------------------------------------------
8. datepart()
功能:日期date按datepart风格之后变成字符串
语法:datename (datepart,date)
datepart列表(day,month,year,hour,minute,second,week,weekday)
代码:
-----------------------------------------------------------
9. day()
功能:求日期的天
语法:day(date)
代码:select day(current_timestamp)
-----------------------------------------------------------
10. getdate()
功能:求当前日期和时间
语法:getdate()
代码:select getdate() 和select current_timestamp相同
-----------------------------------------------------------
11. getutcdate()
-----------------------------------------------------------
12. isdate()
-----------------------------------------------------------
13. month()
功能:求日期的月
语法:month(date)
代码:select month(current_timestamp)
-----------------------------------------------------------
14. year()
功能:求日期的年
语法:year(date)
代码:select year(current_timestamp)
-----------------------------------------------------------
5.5数学函数math functions
1. abs()
2. acos()
3. asin()
4. atan()
5. ceiling()
6. cos()
7. cot()
8. degrees()
9. exp()
10. floor()
11. isnumeric()
12. log()
13. log10()
14. pi()
15. power()
16. radians()
11. 17. rand()
18. round()
19. sign()
20. sin()
21. sqrt()
22. square()
23. tan()
-----------------------------------------------------------
5.6分析函数analytical functions
1. compute()
2. cube()
3. dense_rank()
4. grouping()
5. ntile()
6. partition()
7. pivot()
8. rollup()
9. row_number()
10. stdev()
11. stdevp()
12. var()
13. varp()
/**********************************************************/
6.transact sql
6.1数据类型data types
6.2脚本语法sytanx
6.3脚本游标cursor
6.4存储过程procedure
6.5存储函数function
6.6触发器trigger
6.7事务transaction
6.8其它other
/**********************************************************/
6.1数据类型data types
1. bigint
2. bit
3. bitwise operators
4. char
5. collate
6. create type
7. data type
8. date type
9. datetime
10. decimal
11. float
12. fulltext
13. integer
14. large text
15. money
16. nchar
17. nvarchar
18. openrowset
19. readtext
20. smalldatetime
21. smallint
22. sql_variant
23. text
24. textptr
25. timestamp
26. varbinary
27. varchar
28. writetext
29. unicode
-----------------------------------------------------------
6.2脚本语法syntax
6.2.0局部/全局变量定义
局部变量 (以@开头)
格式:declare @变量名 数据类型
代码:declare @x int
全局变量 (必须以@@开头)
格式:declare @@变量名 类型
代码:select @@id = '10010001'
6.2.1块语句
格式:
begin
...
end
-----------------------------------------------------------
6.2.2赋值语句set/select
set @id = '10010001'
select @id = '10010001'
6.2.3条件语句(if/case)
6.2.3.1 if语句
declare @x int @y int @z int
select @x = 1 @y = 2 @z=3
if @x > @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 @i<=3
begin
set @hundreds=cast(substring(@s,@i*3+1,1) as int)--百位0-9
set @tenth=cast(substring(@s,@i*3+2,1) as int)
set @one=(case @tenth when 1 then 10 else 0 end)+cast(substring(@s,@i*3+3,1) as int)--个位0-19
set @tenth=(case when @tenth<=1 then 0 else @tenth end)--十位0、2-9
if (@i=1 and @billion>0 and (@million>0 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 @tenth<=9
begin
if @hundreds>0
set @result=@result+' and '
set @result=@result+rtrim(substring(@numbers,@tenth*10+171,10))
end
if @one>=1 and @one<=19
begin
if @tenth>0
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<=14
begin
set @n_str=substring(@n_data,@i,1)
if @n_str<>' '
begin
if not ((substring(@n_data,@i,2)='00') or ((@n_str='0') and ((@i=4) or (@i=8) or (@i=12) or (@i=14))))
set @c_data=@c_data+substring('零壹贰叁肆伍陆柒捌玖',cast(@n_str as int)+1,1)
if not ((@n_str='0') and (@i<>4) and (@i<>8) and (@i<>12))
set @c_data=@c_data+substring('仟佰拾亿仟佰拾万仟佰拾元角分',@i,1)
if substring(@c_data,len(@c_data)-1,2)='亿万'
set @c_data=substring(@c_data,1,len(@c_data)-1)
end
set @i=@i+1
end
if @num<0
set @c_data='负'+@c_data
if @num=0
set @c_data='零元'
if @n_str='0'
set @c_data=@c_data+'整'
return(@c_data)
end
//测试函数
select name, gz,dbo.f_amt_to_chn(gz) as 中文金额,dbo.f_amt_to_eng(gz) as 英文金额 from tb_hr_gz
//删除函数
语法:
drop function <函数名称>
代码:
drop function f_num_to_eng
-----------------------------------------------------------
6.6触发器trigger
22. 1. trigger( 14 ) 22. 10. trigger order( 2 )
22. 2. alter trigger( 4 ) 22. 11. drop trigger( 2 )
22. 3. trigger for after( 4 ) 22. 12. columns_updated( 1 )
22. 4. trigger for delete( 4 ) 22. 13. update function( 3 )
22. 5. trigger for insert( 1 ) 22. 14. deleted table( 2 )
22. 6. trigger for update( 4 ) 22. 15. inserted table( 5 )
22. 7. trigger on database( 2 ) 22. 16. recursive_triggers( 1 )
22. 8. trigger on server( 1 ) 22. 17. utility trigger( 4 )
22. 9. trigger on view( 3 )
//触发器建立
语法:
create trigger <触发器名称> on <表名>
[for insert | update | delete]
as
[定义变量]
begin
{代码块...}
end
代码0:
复制代码 代码如下:
create trigger tg_tb_hr_bm on tb_hr_bm
for insert,update,delete
as
declare @bm_d varchar(20)
declare @bm_i varchar(20)
begin
set @bm_d=(select bm from deleted)
set @bm_i=(select bm from inserted)
if exists(select * from tb_hr_gz ,deleted where(tb_hr_gz.bm =deleted.bm ))
begin
update tb_hr_gz set bm='' where bm =@bm_d
end
if update(bm)
begin
update tb_hr_gz set bm=@bm_i where bm =@bm_i
end
end
//删除触发器
语法:
drop trigger <触发器名称>
代码:
drop trigger tg_w_house_center
-----------------------------------------------------------
6.7事务transaction
事务(commit/rollback)
set transaction --定义当前事务数据访问特征
commit --提交当前事务
rollback --取消当前事务