SQL语句先前写的时候,很容易把一些特殊的用法忘记,我特此整理了一下SQL语句操作。 w-:
D
v MWC(m
6y@<?08Q
一、基础 @3 "DBJ
1、说明:创建数据库 MVAc8d S
CREATE DATABASE database-name % +8
2、说明:删除数据库 Y n>{4BZ>#
drop database dbname ngqUH
3、说明:备份sql server ,4Y sZ
--- 创建 备份数据的 device GTFl}t
USE master ;U7t
EXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1.dat' ZOHRUm
--- 开始 备份 w:R]!e_6\9
BACKUP DATABASE pubs TO testBack J~2CD*v
4、说明:创建新表 m/N(%oMWB=
create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..) M=Is9)y
根据已有的表创建新表: }2xb&6g~o
A:create table tab_new like tab_old (使用旧表创建新表) f[M"EMy
B:create table tab_new as select col1,col2... from tab_old definition only *lq7t2
5、说明:删除新表 6cZ C
drop table tabname ]Hj`2\KD.d
6、说明:增加一个列 hGKdGu`0
Alter table tabname add column col type \]GGVI;u
注:列增加后将不能删除。DB2中列加上后数据类型也不能改变,唯一能改变的是增加varchar类型的长度。 I)uASfT$
7、说明:添加主键: Alter table tabname add primary key(col) {q2<KRU2+#
说明:删除主键: Alter table tabname drop primary key(col) B)d@RAk
8、说明:创建索引:create [unique] index idxname on tabname(col....) m[#%/
删除索引:drop index idxname Oi#k:vq4
注:索引是不可更改的,想更改必须删除重新建。 ]=pWZ~A
9、说明:创建视图:create view viewname as select statement { r X5
删除视图:drop view viewname ~pwY6Q
10、说明:几个简单的基本的sql语句 u"joCZ7`kG
选择:select * from table1 where 范围 zN/Gy}
插入:insert into table1(field1,field2) values(value1,value2) #|D:f~"d3
删除:delete from table1 where 范围 <sF!]R&4
更新:update table1 set field1=value1 where 范围 m"1
?
查找:select * from table1 where field1 like '%value1%' ---like的语法很精妙,查资料! BC&^]M
排序:select * from table1 order by field1,field2 [desc] `}n0=E
总数:select count as totalcount from table1 M%77u=m
求和:select sum(field1) as sumvalue from table1 XAGiu;<,=
平均:select avg(field1) as avgvalue from table1 B)(w%\M4^
最大:select max(field1) as maxvalue from table1 c{ZqQtfM
最小:select min(field1) as minvalue from table1 ;W =by2x*
+0)5H>h
JCBnFrP
$M%}Oz3*
11、说明:几个高级查询运算词 T)*l' g'
[kQ"6wh8
$jDD0<F.#
A: UNION 运算符 %0go%_
UNION 运算符通过组合其他两个结果表(例如 TABLE1 和 TABLE2)并消去表中任何重复行而派生出一个结果表。当 ALL 随 UNION 一起使用时(即 UNION ALL),不消除重复行。两种情况下,派生表的每一行不是来自 TABLE1 就是来自 TABLE2。 !vi4*
@:
B: EXCEPT 运算符 Y-?51g [u
EXCEPT 运算符通过包括所有在 TABLE1 中但不在 TABLE2 中的行并消除所有重复行而派生出一个结果表。当 ALL 随 EXCEPT 一起使用时 (EXCEPT ALL),不消除重复行。 o<Ke3?J\
C: INTERSECT 运算符 jh-kCF
INTERSECT 运算符通过只包括 TABLE1 和 TABLE2 中都有的行并消除所有重复行而派生出一个结果表。当 ALL 随 INTERSECT 一起使用时 (INTERSECT ALL),不消除重复行。 k0R,!F
注:使用运算词的几个查询结果行必须是一致的。 -U&098}<K
12、说明:使用外连接 uV#-8a5!
A、left outer join: 8VKb*
左外连接(左连接):结果集几包括连接表的匹配行,也包括左连接表的所有行。 ">rsA&hN-
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 nT(!HDH
B:right outer join: 30:HRF(:
右外连接(右连接):结果集既包括连接表的匹配连接行,也包括右连接表的所有行。 U5T^S
C:full outer join: sT@u3^>
全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录。 !;6W!%t.|
4d,qXSKty
75' Ua$
二、提升 g5?r9e
1、说明:复制表(只复制结构,源表名:a 新表名:b) (Access可用) 4"rb&$E
法一:select * into b from a where 1<>1 wK/}E h\^
法二:select top 0 * into b from a @|JPE%T
2、说明:拷贝表(拷贝数据,源表名:a 目标表名:b) (Access可用) xow6@M,
insert into b(a, b, c) select d,e,f from b; xUV_2n+
3、说明:跨数据库之间表的拷贝(具体数据使用绝对路径) (Access可用) 2*b#+ b
insert into b(a, b, c) select d,e,f from b in '具体数据库' where 条件 g#pIMA#/
例子:..from b in '"&Server.MapPath(".")&"\data.mdb" &"' where.. B`t)rBy
4、说明:子查询(表名1:a 表名2:b) 3g4vpKg6c
select a,b,c from a where a IN (select d from b ) 或者: select a,b,c from a where a IN (1,2,3)
~`a#h#
5、说明:显示文章、提交人和最后回复时间 -sruxF
select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b hPNQGVv
6、说明:外连接查询(表名1:a 表名2:b) Mr@<ZTw
select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c xV
}:M
7、说明:在线视图查询(表名1:a ) il 8A&`%
select * from (SELECT a,b,c FROM a) T where t.a > 1; 7cJO)cm0'
8、说明:between的用法,between限制查询数据范围时包括了边界值,not between不包括 `*.r'k2R
select * from table1 where time between time1 and time2 )4 VLm
select a,b,c, from table1 where a not between 数值1 and 数值2 }Etd#">
9、说明:in 的使用方法 l[ZQ7$kL
select * from table1 where a [not] in ('值1','值2','值4','值6') IDL^0:eg<.
10、说明:两张关联表,删除主表中已经在副表中没有的信息 ?ZD{e|:u
delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 ) Q7OnhGA
11、说明:四表联查问题: o)$Q]N##
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 ..... {g23[$X]N
12、说明:日程安排提前五分钟提醒 ~50y-
SQL: select * from 日程安排 where datediff('minute',f开始时间,getdate())>5 QZz{74]n
13、说明:一条sql 语句搞定数据库分页 kfG 65aa>_
select top 10 b.* from (select top 20 主键字段,排序字段 from 表名 order by 排序字段 desc) a,表名 b where b.主键字段 = a.主键字段 order by a.排序字段 C>\h?<s
14、说明:前10条记录 I=3B
5u
select top 10 * form table1 where 范围 fS'k;r*r
15、说明:选择在每一组b值相同的数据中对应的a最大的记录的所有信息(类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等.) (PE8H~d
select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b) 9|?(GG
16、说明:包括所有在 TableA 中但不在 TableB和TableC 中的行并消除所有重复行而派生出一个结果表 T5X'D(\|
(select a from tableA ) except (select a from tableB) except (select a from tableC) R-0_226
17、说明:随机取出10条数据 J_((o
select top 10 * from tablename order by newid() 0YTtA]|`4
18、说明:随机选择记录 )e <! =S
select newid() d%[`=fs]|m
19、说明:删除重复记录 E?;T:7.%
Delete from tablename where id not in (select max(id) from tablename group by col1,col2,...) yScov)dp(
20、说明:列出数据库里所有的表名 _g/TH-;^
select name from sysobjects where type='U' ,EGD8$RA]
21、说明:列出表里的所有的 g)|++?
select name from syscolumns where id=object_id('TableName') t,r&SrC
22、说明:列示type、vender、pcs字段,以type字段排列,case可以方便地实现多重选择,类似select 中的case。 Bb2r95h}^
select type,sum(case vender when 'A' then pcs else 0 end),sum(case vender when 'C' then pcs else 0 end),sum(case vender when 'B' then pcs else 0 end) FROM tablename group by type v1tN
DyM6
显示结果: &>wce5uV
type vender pcs OKLggim{
电脑 A 1 y:|Xg0Kp
电脑 A 1 E]U3O>hf
光盘 B 2 {"@b`
光盘 A 2 1RUbY>K#U
手机 B 3 E?c{02fu
手机 C 3 U!-+v:SF
23、说明:初始化表table1 Xxsnpb>
TRUNCATE TABLE table1 $y]||tX
24、说明:选择从10到15的记录 /B#lju!
select top 5 * from (select top 15 * from table order by id asc) table_别名 order by id desc e7)%=F/)
<:yq~?
.8uwg@yD
9'*ZEl^?D
三、技巧 {J6sM$aj
1、1=1,1=2的使用,在SQL语句组合时用的较多 d ;7pri)B
"where 1=1" 是表示选择全部 "where 1=2"全部不选, ek.WuOs
如: {ALBmSapK"
if @strWhere !='' 1&dsQ,VDl
begin cTIwA:)D
set @strSQL = 'select count(*) as Total from [' + @tblName + '] where ' + @strWhere }+RF~~H/
end zt>_)&b
else "VVR#H}{
begin 8KELN(o$ 7
set @strSQL = 'select count(*) as Total from [' + @tblName + ']' Wj{Rp{}3
end BnnUUaE
我们可以直接写成 ]ieA?:0Hi
set @strSQL = 'select count(*) as Total from [' + @tblName + '] where 1=1 安定 '+ @strWhere x_iy;\s1
2、收缩数据库 ZT6X4 Z
--重建索引 AqKx3p6
DBCC REINDEX en#g<on
DBCC INDEXDEFRAG eYSGxcx
--收缩数据和日志 $^D(%
DBCC SHRINKDB zam0(^=
DBCC SHRINKFILE :AcNb
3、压缩数据库 $$;2jX"I
dbcc shrinkdatabase(dbname) '<W,-i
4、转移数据库给新用户以已存在用户权限 4bJ2<j
exec sp_change_users_login 'update_one','newname','oldname' ?;#3U5$v
go J]^gF|
5、检查备份集 }br<2?y,
RESTORE VERIFYONLY from disk='E:\dvbbs.bak' 88=FPEU
6、修复数据库 cyP*QW[
ALTER DATABASE [dvbbs] SET SINGLE_USER .dLX'84fY
GO pz6-
hi7
DBCC CHECKDB('dvbbs',repair_allow_data_loss) WITH TABLOCK r~!%w(N|M
GO 9n\#s~,
ALTER DATABASE [dvbbs] SET MULTI_USER B+[Q$Q"
GO \V-
Y,!~5
7、日志清除 MdboWE5i
SET NOCOUNT ON #V,~d&_k
DECLARE @LogicalFileName sysname, IV#f}NrfD
@MaxMinutes INT, Ty|c@X
@NewSize INT #2'&=?J1r
USE tablename -- 要操作的数据库名 WHavz0knf[
SELECT @LogicalFileName = 'tablename_log', -- 日志文件名 ; Kb[UZ1
@MaxMinutes = 10, -- Limit on time allowed to wrap log. LuQ
M$/i
@NewSize = 1 -- 你想设定的日志文件的大小(M) n~i4yn=
-- Setup / initialize VP[!ji9P
DECLARE @OriginalSize int Gz5@1CF
SELECT @OriginalSize = size ? /X6x1PN
FROM sysfiles tYNt>9L|
WHERE name = @LogicalFileName Nv]/L+i
SELECT 'Original Size of ' + db_name() + ' LOG is ' + c Yn}we}7
CONVERT(VARCHAR(30),@OriginalSize) + ' 8K pages or ' + 1% %Tm"
CONVERT(VARCHAR(30),(@OriginalSize*8/1024)) + 'MB' /,%o<Ql9
FROM sysfiles moI<b\G@
WHERE name = @LogicalFileName X.Y)'qSf
CREATE TABLE DummyTrans )g^Ewzy^X
(DummyColumn char (8000) not null) &_9eg
DECLARE @Counter INT, }'v?Qq
@StartTime DATETIME, 3evfX[V#
@TruncLog VARCHAR(255) ,lYU#Hx*
SELECT @StartTime = GETDATE(), 0=zS&xM
@TruncLog = 'BACKUP LOG ' + db_name() + ' WITH TRUNCATE_ONLY' KCT"a:\
DBCC SHRINKFILE (@LogicalFileName, @NewSize) "$;:dfrU
EXEC (@TruncLog) {v/6|
-- Wrap the log if necessary. JT ^0AZ_*
WHILE @MaxMinutes > DATEDIFF (mi, @StartTime, GETDATE()) -- time has not expired 4DM|OL`w
AND @OriginalSize = (SELECT size FROM sysfiles WHERE name = @LogicalFileName) Yaepy3F
AND (@OriginalSize * 8 /1024) > @NewSize I
T2sS6&R
BEGIN -- Outer loop. HW,55#yG
SELECT @Counter = 0 {X"]92+
WHILE ((@Counter < @OriginalSize / 16) AND (@Counter < 50000)) p5t#d)
BEGIN -- update pra&A2Y\
INSERT DummyTrans VALUES ('Fill Log') EPnB%'l\c
DELETE DummyTrans #T`+~tW'|
SELECT @Counter = @Counter + 1 *heQ@ww
END [kkcV5I-
EXEC (@TruncLog) Z}S tA0F_
END ,R6$SrNcd
SELECT 'Final Size of ' + db_name() + ' LOG is ' + - $/{V&?t
CONVERT(VARCHAR(30),size) + ' 8K pages or ' + <L#r6y~H
CONVERT(VARCHAR(30),(size*8/1024)) + 'MB'
S6Pb V}
FROM sysfiles YL0RQa
WHERE name = @LogicalFileName - & r{%7
DROP TABLE DummyTrans lB@K;E@r8
SET NOCOUNT OFF +c_CYkHJ/
8、说明:更改某个表 ?V&a |:N9
exec sp_changeobjectowner 'tablename','dbo' J/2pS
9、存储更改全部表 +q%goG8
CREATE PROCEDURE dbo.User_ChangeObjectOwnerBatch W)O'( D
@OldOwner as NVARCHAR(128), El}z^e
@NewOwner as NVARCHAR(128) 4`]1W,t
AS Sp:de,9@
DECLARE @Name as NVARCHAR(128) w Vmy`OV/
DECLARE @Owner as NVARCHAR(128) ~;Kl/Z
DECLARE @OwnerName as NVARCHAR(128) ^[akB|#\9
DECLARE curObject CURSOR FOR 8;rS"!qM
select 'Name' = name, d<e.`dhc
'Owner' = user_name(uid) -&tiM
v
from sysobjects CB)#;
|aDB
where user_name(uid)=@OldOwner 4ebGAg ?_
order by name <0}'#9>O
OPEN curObject ]uf_"D
FETCH NEXT FROM curObject INTO @Name, @Owner +M:Q!'
WHILE(@@FETCH_STATUS=0) +__Rk1CVh
BEGIN 9hU@VPB~
if @Owner=@OldOwner T94$}- 5/)
begin d0az#Yg!
set @OwnerName = @OldOwner + '.' + rtrim(@Name) d?.x./1[qi
exec sp_changeobjectowner @OwnerName, @NewOwner "'(4l 2.
end 24fWj?A| ^
-- select @name,@NewOwner,@OldOwner !2}Q9a
FETCH NEXT FROM curObject INTO @Name, @Owner :8g \B{
END 'Ud5;?{
close curObject ]W,g>91m
deallocate curObject 0kfw8Lon
GO u:$x,Q
10、SQL SERVER中直接循环写入数据 0Jr<>7Q1
declare @i int I%`2RXBt3^
set @i=1 &-A7%"
while @i<30 Z(P#]jI]
begin Xqk$[peS
insert into test (userid) values(@i) G <q@K-
set @i=@i+1 HS7!O
end sEa:p:!
小记存储过程中经常用到的本周,本月,本年函数 Kkm7L-
Dateadd(wk,datediff(wk,0,getdate()),-1) hAdEq$
Dateadd(wk,datediff(wk,0,getdate()),6) \N)FUYoHg
Dateadd(mm,datediff(mm,0,getdate()),0) ^9i^Ci9
Dateadd(ms,-3,dateadd(mm,datediff(m,0,getdate())+1,0)) j&9~OXYv
Dateadd(yy,datediff(yy,0,getdate()),0) #0c`"2t&M
Dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate())+1, 0)) 2_Qzc&"[
4
上面的SQL代码只是一个时间段 <4Fd~
Dateadd(wk,datediff(wk,0,getdate()),-1) yLP0w^Q
Dateadd(wk,datediff(wk,0,getdate()),6) !8$}]uWP
就是表示本周时间段. yY+2;`CH
下面的SQL的条件部分,就是查询时间段在本周范围内的: nJnan,`W
Where Time BETWEEN Dateadd(wk,datediff(wk,0,getdate()),-1) AND Dateadd(wk,datediff(wk,0,getdate()),6) b8Qm4 b?:4
而在存储过程中 *HRRv.iQ
select @begintime = Dateadd(wk,datediff(wk,0,getdate()),-1) +-"#GL~cC
select @endtime = Dateadd(wk,datediff(wk,0,getdate()),6) @N$r'@