当前位置: 移动技术网 > IT编程>数据库>MSSQL > sql 常用技巧整理

sql 常用技巧整理

2017年12月12日  | 移动技术网IT编程  | 我要评论

钟明照,恶作剧二吻吻戏,搞笑漫画图片

--语 句 功 能
--数据操作
select --从数据库表中检索数据行和列
insert --向数据库表添加新数据行
delete --从数据库表中删除数据行
update --更新数据库表中的数据
--数据定义
create table --创建一个数据库表
drop table --从数据库中删除表
alter table --修改数据库表结构
create view --创建一个视图
drop view --从数据库中删除视图
create index --为数据库表创建一个索引
drop index --从数据库中删除索引
create procedure --创建一个存储过程
drop procedure --从数据库中删除存储过程
create trigger --创建一个触发器
drop trigger --从数据库中删除触发器
create schema --向数据库添加一个新模式
drop schema --从数据库中删除一个模式
create domain --创建一个数据值域
alter domain --改变域定义
drop domain --从数据库中删除一个域
--数据控制
grant --授予用户访问权限
deny --拒绝用户访问
revoke --解除用户访问权限
--事务控制
commit --结束当前事务
rollback --中止当前事务
set transaction --定义当前事务数据访问特征
--程序化sql
declare --为查询设定游标
explan --为查询描述数据访问计划
open --检索查询结果打开一个游标
fetch --检索一行查询结果
close --关闭游标
prepare --为动态执行准备sql 语句
execute --动态地执行sql 语句
describe --描述准备好的查询


---局部变量
declare @id char(10)
--set @id = '10010001'
select @id = '10010001'


---全局变量
---必须以@@开头


--if else
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'


--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


--while continue break
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


--waitfor
--例 等待1 小时2 分零3 秒后才执行select 语句
waitfor delay '01:02:03'
select * from employee
--例 等到晚上11 点零8 分后才执行select 语句
waitfor time '23:08:00'
select * from employee


***select***


select *(列名) from table_name(表名) where column_name operator value
ex:(宿主)
select * from stock_information where stockid = str(nid)
stockname = 'str_name'
stockname like '% find this %'
stockname like '[a-za-z]%' --------- ([]指定值的范围)
stockname like '[^f-m]%' --------- (^排除指定范围)
--------- 只能在使用like关键字的where子句中使用通配符)
or stockpath = 'stock_path'
or stocknumber < 1000
and stockindex = 24
not stock*** = 'man'
stocknumber between 20 and 100
stocknumber in(10,20,30)
order by stockid desc(asc) --------- 排序,desc-降序,asc-升序
order by 1,2 --------- by列号
stockname = (select stockname from stock_information where stockid = 4)
--------- 子查询
--------- 除非能确保内层select只返回一个行的值,
--------- 否则应在外层where子句中用一个in限定符
select distinct column_name form table_name --------- distinct指定检索独有的列值,不重复
select stocknumber ,"stocknumber + 10" = stocknumber + 10 from table_name
select stockname , "stocknumber" = count(*) from table_name group by stockname
--------- group by 将表按行分组,指定列中有相同的值
having count(*) = 2 --------- having选定指定的组

select *
from table1, table2
where table1.id *= table2.id -------- 左外部连接,table1中有的而table2中没有得以null表示
table1.id =* table2.id -------- 右外部连接


select stockname from table1
union [all] ----- union合并查询结果集,all-保留重复行
select stockname from table2


***insert***


insert into table_name (stock_name,stock_number) value ("xxx","xxxx")
value (select stockname , stocknumber from stock_table2)---value为select语句


***update***


update table_name set stockname = "xxx" [where stockid = 3]
stockname = default
stockname = null
stocknumber = stockname + 4


***delete***


delete from table_name where stockid = 3
truncate table_name ----------- 删除表中所有行,仍保持表的完整性
drop table table_name --------------- 完全删除表


***alter table*** --- 修改数据库表结构


alter table database.owner.table_name add column_name char(2) null .....
sp_help table_name ---- 显示表已有特征
create table table_name (name char(20), age smallint, lname varchar(30))
insert into table_name select ......... ----- 实现删除列的方法(创建新表)
alter table table_name drop constraint stockname_default ---- 删除stockname的default约束

***function(/*常用函数*/)***


----统计函数----
avg --求平均值
count --统计数目
max --求最大值
min --求最小值
sum --求和


--avg
use pangu
select avg(e_wage) as dept_avgwage
from employee
group by dept_id


--max
--求工资最高的员工姓名
use pangu
select e_name
from employee
where e_wage =
(select max(e_wage)
from employee)


--stdev()
--stdev()函数返回表达式中所有数据的标准差


--stdevp()
--stdevp()函数返回总体标准差


--var()
--var()函数返回表达式中所有值的统计变异数


--varp()
--varp()函数返回总体变异数


----算术函数----


/***三角函数***/
sin(float_expression) --返回以弧度表示的角的正弦
cos(float_expression) --返回以弧度表示的角的余弦
tan(float_expression) --返回以弧度表示的角的正切
cot(float_expression) --返回以弧度表示的角的余切
/***反三角函数***/
asin(float_expression) --返回正弦是float 值的以弧度表示的角
acos(float_expression) --返回余弦是float 值的以弧度表示的角
atan(float_expression) --返回正切是float 值的以弧度表示的角
atan2(float_expression1,float_expression2)
--返回正切是float_expression1 /float_expres-sion2的以弧度表示的角
degrees(numeric_expression)
--把弧度转换为角度返回与表达式相同的数据类型可为
--integer/money/real/float 类型
radians(numeric_expression) --把角度转换为弧度返回与表达式相同的数据类型可为
--integer/money/real/float 类型
exp(float_expression) --返回表达式的指数值
log(float_expression) --返回表达式的自然对数值
log10(float_expression)--返回表达式的以10 为底的对数值
sqrt(float_expression) --返回表达式的平方根
/***取近似值函数***/
ceiling(numeric_expression) --返回>=表达式的最小整数返回的数据类型与表达式相同可为
--integer/money/real/float 类型
floor(numeric_expression) --返回<=表达式的最小整数返回的数据类型与表达式相同可为
--integer/money/real/float 类型
round(numeric_expression) --返回以integer_expression 为精度的四舍五入值返回的数据
--类型与表达式相同可为integer/money/real/float 类型
abs(numeric_expression) --返回表达式的绝对值返回的数据类型与表达式相同可为
--integer/money/real/float 类型
sign(numeric_expression) --测试参数的正负号返回0 零值1 正数或-1 负数返回的数据类型
--与表达式相同可为integer/money/real/float 类型
pi() --返回值为π 即3.1415926535897936
rand([integer_expression]) --用任选的[integer_expression]做种子值得出0-1 间的随机浮点数


----字符串函数----
ascii() --函数返回字符表达式最左端字符的ascii 码值
char() --函数用于将ascii 码转换为字符
--如果没有输入0 ~ 255 之间的ascii 码值char 函数会返回一个null 值
lower() --函数把字符串全部转换为小写
upper() --函数把字符串全部转换为大写
str() --函数把数值型数据转换为字符型数据
ltrim() --函数把字符串头部的空格去掉
rtrim() --函数把字符串尾部的空格去掉
left(),right(),substring() --函数返回部分字符串
charindex(),patindex() --函数返回字符串中某个指定的子串出现的开始位置
soundex() --函数返回一个四位字符码
--soundex函数可用来查找声音相似的字符串但soundex函数对数字和汉字均只返回0 值
difference() --函数返回由soundex 函数返回的两个字符表达式的值的差异
--0 两个soundex 函数返回值的第一个字符不同
--1 两个soundex 函数返回值的第一个字符相同
--2 两个soundex 函数返回值的第一二个字符相同
--3 两个soundex 函数返回值的第一二三个字符相同
--4 两个soundex 函数返回值完全相同


quotename() --函数返回被特定字符括起来的字符串
/*select quotename('abc', '{') quotename('abc')
运行结果如下
----------------------------------{
{abc} [abc]*/


replicate() --函数返回一个重复character_expression 指定次数的字符串
/*select replicate('abc', 3) replicate( 'abc', -2)
运行结果如下
----------- -----------
abcabcabc null*/


reverse() --函数将指定的字符串的字符排列顺序颠倒
replace() --函数返回被替换了指定子串的字符串
/*select replace('abc123g', '123', 'def')
运行结果如下
----------- -----------
abcdefg*/


space() --函数返回一个有指定长度的空白字符串
stuff() --函数用另一子串替换字符串指定位置长度的子串


----数据类型转换函数----
cast() 函数语法如下
cast() (<expression> as <data_ type>[ length ])
convert() 函数语法如下
convert() (<data_ type>[ length ], <expression> [, style])


select cast(100+99 as char) convert(varchar(12), getdate())
运行结果如下
------------------------------ ------------
199 jan 15 2000


----日期函数----
day() --函数返回date_expression 中的日期值
month() --函数返回date_expression 中的月份值
year() --函数返回date_expression 中的年份值
dateadd(<datepart> ,<number> ,<date>)
--函数返回指定日期date 加上指定的额外日期间隔number 产生的新日期
datediff(<datepart> ,<number> ,<date>)
--函数返回两个指定日期在datepart 方面的不同之处
datename(<datepart> , <date>) --函数以字符串的形式返回日期的指定部分
datepart(<datepart> , <date>) --函数以整数值的形式返回日期的指定部分
getdate() --函数以datetime 的缺省格式返回系统当前的日期和时间


----系统函数----
app_name() --函数返回当前执行的应用程序的名称
coalesce() --函数返回众多表达式中第一个非null 表达式的值
col_length(<'table_name'>, <'column_name'>) --函数返回表中指定字段的长度值
col_name(<table_id>, <column_id>) --函数返回表中指定字段的名称即列名
datalength() --函数返回数据表达式的数据的实际长度
db_id(['database_name']) --函数返回数据库的编号
db_name(database_id) --函数返回数据库的名称
host_id() --函数返回服务器端计算机的名称
host_name() --函数返回服务器端计算机的名称
identity(<data_type>[, seed increment]) [as column_name])
--identity() 函数只在select into 语句中使用用于插入一个identity column列到新表中
/*select identity(int, 1, 1) as column_name
into newtable
from oldtable*/
isdate() --函数判断所给定的表达式是否为合理日期
isnull(<check_expression>, <replacement_value>) --函数将表达式中的null 值用指定值替换
isnumeric() --函数判断所给定的表达式是否为合理的数值
newid() --函数返回一个uniqueidentifier 类型的数值
nullif(<expression1>, <expression2>)
--nullif 函数在expression1 与expression2 相等时返回null 值若不相等时则返回expression1 的值
精妙sql语句
说明:复制表(只复制结构,源表名:a 新表名:b)
sql: select * into b from a where 1<>1
说明:拷贝表(拷贝数据,源表名:a 目标表名:b)
sql: insert into b(a, b, c) select d,e,f from b;
说明:显示文章、提交人和最后回复时间
sql: select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b
说明:外连接查询(表名1:a 表名2:b)
sql: select a.a, a.b, a.c, b.c, b.d, b.f from a left out join b on a.a = b.c
说明:日程安排提前五分钟提醒
sql: select * from 日程安排 where datediff('minute',f开始时间,getdate())>5

说明:两张关联表,删除主表中已经在副表中没有的信息
sql:
delete from info where not exists ( select * from infobz where info.infid=infobz.infid )
说明:--
sql:
select a.num, a.name, b.upd_date, b.prev_upd_date
from table1,
(select x.num, x.upd_date, y.upd_date prev_upd_date
from (select num, upd_date, inbound_qty, stock_onhand
from table2
where to_char(upd_date,'yyyy/mm') = to_char(sysdate, 'yyyy/mm')) x,
(select num, upd_date, stock_onhand
from table2
where to_char(upd_date,'yyyy/mm') =
to_char(to_date(to_char(sysdate, 'yyyy/mm') || '/01','yyyy/mm/dd') - 1, 'yyyy/mm') ) y,
where x.num = y.num (+)
and x.inbound_qty + nvl(y.stock_onhand,0) <> x.stock_onhand ) b
where a.num = b.num
说明:--
sql:
select * from studentinfo where not exists(select * from student where studentinfo.id=student.id) and 系名称='"&strdepartmentname&"' and 专业名称='"&strprofessionname&"' order by 性别,生源地,高考总成绩
说明:
从数据库中去一年的各单位电话费统计(电话费定额贺电化肥清单两个表来源)
sql:
select a.userper, a.tel, a.standfee, to_char(a.telfeedate, 'yyyy') as telyear,
sum(decode(to_char(a.telfeedate, 'mm'), '01', a.factration)) as jan,
sum(decode(to_char(a.telfeedate, 'mm'), '02', a.factration)) as fri,
sum(decode(to_char(a.telfeedate, 'mm'), '03', a.factration)) as mar,
sum(decode(to_char(a.telfeedate, 'mm'), '04', a.factration)) as apr,
sum(decode(to_char(a.telfeedate, 'mm'), '05', a.factration)) as may,
sum(decode(to_char(a.telfeedate, 'mm'), '06', a.factration)) as jue,
sum(decode(to_char(a.telfeedate, 'mm'), '07', a.factration)) as jul,
sum(decode(to_char(a.telfeedate, 'mm'), '08', a.factration)) as agu,
sum(decode(to_char(a.telfeedate, 'mm'), '09', a.factration)) as sep,
sum(decode(to_char(a.telfeedate, 'mm'), '10', a.factration)) as oct,
sum(decode(to_char(a.telfeedate, 'mm'), '11', a.factration)) as nov,
sum(decode(to_char(a.telfeedate, 'mm'), '12', a.factration)) as dec
from (select a.userper, a.tel, a.standfee, b.telfeedate, b.factration
from telfeestand a, telfee b
where a.tel = b.telfax) a
group by a.userper, a.tel, a.standfee, to_char(a.telfeedate, 'yyyy')
说明:四表联查问题:
sql: select * from a left inner join b on a.a=b.b right inner join c on a.a=c.c inner join d on a.a=d.d where .....
说明:得到表中最小的未使用的id号
sql:
select (case when exists(select * from handle b where b.handleid = 1) then min(handleid) + 1 else 1 end) as handleid
from handle
where not handleid in (select a.handleid - 1 from handle a)

: 我在ms sql中建了一个表,可由于种种原因有些记录重复了
: 记录完全的一模一样。
: 现在我想把重复的都删掉,只保留重复记录中的第一条。
: 我在database好象看到有介绍oracle的,

select distinct * into #table_name from table_name
delete from table_name
select * into table_name from #table_name
drop table #table_name

与此相关的是“select into”选项,可以在数据库属性
对话框中,勾起来此项,或者在query analyzer中执行
execute sp_dboption 'db_name','select into','true'
开启。默认值是关闭的。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网