SQL语句先前写的时候,很容易把一些特殊的用法忘记,我特此整理了一下SQL语句操作。 N;BuBm5K
T5e#Ll/
R^sgafGl=
一、基础 )Y'g;
1、说明:创建数据库 ZNk[Jn
[.
CREATE DATABASE database-name {hN<Ot
2、说明:删除数据库 !7Qj8YmS
drop database dbname IR:{ { (
3、说明:备份sql server I@O9bxR?
--- 创建 备份数据的 device 8'bZR]
USE master 9IrCu?n9b
EXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1.dat' Mqk|H~l5c
--- 开始 备份 M"{*))O\-c
BACKUP DATABASE pubs TO testBack F$|:'#KN
4、说明:创建新表 ;mz#$"(
create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..) 8fBhX,1
根据已有的表创建新表: *P]]7DR
A:create table tab_new like tab_old (使用旧表创建新表) f8qDmk5s
B:create table tab_new as select col1,col2... from tab_old definition only s|c}9/Xe)
5、说明:删除新表 ]q[(z
drop table tabname gW4fwE^
6、说明:增加一个列 V>Xg\9B_
Alter table tabname add column col type k\*?<g
注:列增加后将不能删除。DB2中列加上后数据类型也不能改变,唯一能改变的是增加varchar类型的长度。 n5BD0q
7、说明:添加主键: Alter table tabname add primary key(col) t0v>J9
说明:删除主键: Alter table tabname drop primary key(col) CyHHV
8、说明:创建索引:create [unique] index idxname on tabname(col....) +/kOUz/]
删除索引:drop index idxname B B'qbX3xK
注:索引是不可更改的,想更改必须删除重新建。 _h,_HW)G
9、说明:创建视图:create view viewname as select statement 3fXrwmBT8
删除视图:drop view viewname 1q5S"=+W[
10、说明:几个简单的基本的sql语句 Q8QB{*4
选择:select * from table1 where 范围 vdB2T2F
插入:insert into table1(field1,field2) values(value1,value2) $)PS#ND&
删除:delete from table1 where 范围 |r?0!;bN0
更新:update table1 set field1=value1 where 范围 ,O-_Pv
查找:select * from table1 where field1 like '%value1%' ---like的语法很精妙,查资料! Jg{K!P|i
排序:select * from table1 order by field1,field2 [desc] Mw-L?j0o[k
总数:select count as totalcount from table1 W?P4oKsql*
求和:select sum(field1) as sumvalue from table1 4${3e
Sg_
平均:select avg(field1) as avgvalue from table1 DTo"{!
最大:select max(field1) as maxvalue from table1 wL>*WLfR
最小:select min(field1) as minvalue from table1 :V#xrH8R
omy3<6
iyr8*L\
99By.+~pX
11、说明:几个高级查询运算词 O0`ofFN
AFvv+
ss
5rCJIl.
A: UNION 运算符 n_LK8
UNION 运算符通过组合其他两个结果表(例如 TABLE1 和 TABLE2)并消去表中任何重复行而派生出一个结果表。当 ALL 随 UNION 一起使用时(即 UNION ALL),不消除重复行。两种情况下,派生表的每一行不是来自 TABLE1 就是来自 TABLE2。 TvT>UBqj=
B: EXCEPT 运算符 3B,dL|q(@J
EXCEPT 运算符通过包括所有在 TABLE1 中但不在 TABLE2 中的行并消除所有重复行而派生出一个结果表。当 ALL 随 EXCEPT 一起使用时 (EXCEPT ALL),不消除重复行。 ~]?EV?T
C: INTERSECT 运算符 KydAFxUb
INTERSECT 运算符通过只包括 TABLE1 和 TABLE2 中都有的行并消除所有重复行而派生出一个结果表。当 ALL 随 INTERSECT 一起使用时 (INTERSECT ALL),不消除重复行。 \T<F#a
注:使用运算词的几个查询结果行必须是一致的。 i;]# @n|
12、说明:使用外连接 !Icznou\
A、left outer join: (Pw,3CbJ
左外连接(左连接):结果集几包括连接表的匹配行,也包括左连接表的所有行。 jTV4iX
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 0c!^=(
B:right outer join: KD+&5=Y
右外连接(右连接):结果集既包括连接表的匹配连接行,也包括右连接表的所有行。 Bj><0
cNF
C:full outer join: 0raFb,6l
全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录。 BI*0JKQu
T \- x3i
\dE{[^.5
二、提升 1uG)U)y/Q
1、说明:复制表(只复制结构,源表名:a 新表名:b) (Access可用) #r?[@aJ
法一:select * into b from a where 1<>1 Pec Zuv
法二:select top 0 * into b from a UGgo;e
2、说明:拷贝表(拷贝数据,源表名:a 目标表名:b) (Access可用) KC2Z@
insert into b(a, b, c) select d,e,f from b; fz|_c*&64
3、说明:跨数据库之间表的拷贝(具体数据使用绝对路径) (Access可用) fGs\R]
insert into b(a, b, c) select d,e,f from b in '具体数据库' where 条件 7^M$u\a)U
例子:..from b in '"&Server.MapPath(".")&"\data.mdb" &"' where.. L ed{#+
4、说明:子查询(表名1:a 表名2:b) j;D$qd'J
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) D0kz;X
5、说明:显示文章、提交人和最后回复时间 uW/>c$*)
select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b [P ;fv
6、说明:外连接查询(表名1:a 表名2:b) BzWkZAX
select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c ?2,D-3 {
7、说明:在线视图查询(表名1:a ) 0o6o<ggi
select * from (SELECT a,b,c FROM a) T where t.a > 1; Jc]66
8、说明:between的用法,between限制查询数据范围时包括了边界值,not between不包括 LN<rBF[_:f
select * from table1 where time between time1 and time2 @W$ha
y
select a,b,c, from table1 where a not between 数值1 and 数值2 ~7g$TAe{
9、说明:in 的使用方法 88[u^aC
select * from table1 where a [not] in ('值1','值2','值4','值6') Q!=`|X|:
10、说明:两张关联表,删除主表中已经在副表中没有的信息 EK0~3HSZ
delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 ) V\r{6-%XiW
11、说明:四表联查问题: _:5t~29
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 ..... $9X?LGUz
12、说明:日程安排提前五分钟提醒 S<'_{u z
SQL: select * from 日程安排 where datediff('minute',f开始时间,getdate())>5 Q2woCxB
13、说明:一条sql 语句搞定数据库分页 Lpkx$QZ
select top 10 b.* from (select top 20 主键字段,排序字段 from 表名 order by 排序字段 desc) a,表名 b where b.主键字段 = a.主键字段 order by a.排序字段 $XMpC{
14、说明:前10条记录 a$^)~2U{
select top 10 * form table1 where 范围 UhkL=+PD
15、说明:选择在每一组b值相同的数据中对应的a最大的记录的所有信息(类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等.) `T7TWv"M
select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b) vRf$#fBEQ
16、说明:包括所有在 TableA 中但不在 TableB和TableC 中的行并消除所有重复行而派生出一个结果表 RF'nwzM3
(select a from tableA ) except (select a from tableB) except (select a from tableC) (RG "2I3
17、说明:随机取出10条数据 5M5vxJ)Lh
select top 10 * from tablename order by newid() |/%5~=%7
18、说明:随机选择记录 fB,eeT1v?h
select newid() -Q?c'e
19、说明:删除重复记录 0a<h,s0"2
Delete from tablename where id not in (select max(id) from tablename group by col1,col2,...) D Y4!RjJ47
20、说明:列出数据库里所有的表名 Gx}`_[-
select name from sysobjects where type='U' zOFHdd ,"g
21、说明:列出表里的所有的 A<TYt
M
select name from syscolumns where id=object_id('TableName') Yh@2m9
22、说明:列示type、vender、pcs字段,以type字段排列,case可以方便地实现多重选择,类似select 中的case。 g&EK^q
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 |42;171
显示结果: AcXVfk z
type vender pcs >b5 ;I1o=y
电脑 A 1 g"Ueo'd*
电脑 A 1 zF{~Md1
光盘 B 2 $Zw+"AA
光盘 A 2 vx' ] ;
手机 B 3 wqV"fZA\]
手机 C 3 `VUJW]wGu
23、说明:初始化表table1 4(oU88z
TRUNCATE TABLE table1 ;~d$OM
24、说明:选择从10到15的记录 >#l:]T
select top 5 * from (select top 15 * from table order by id asc) table_别名 order by id desc
-%%Xx5D
Sj|tR[SAoD
*!*%~h8V
XE2rx2k
三、技巧 .oTS7rYw
1、1=1,1=2的使用,在SQL语句组合时用的较多 LYd:S
"where 1=1" 是表示选择全部 "where 1=2"全部不选, oqhJ2
如: xJU]py~o
if @strWhere !='' y0&vsoT
begin -vY5h%7kf
set @strSQL = 'select count(*) as Total from [' + @tblName + '] where ' + @strWhere t?PqfVSq
end /N<aN9Z<x,
else mXS]SE
begin 6oZHSjC*
set @strSQL = 'select count(*) as Total from [' + @tblName + ']' ]o0]i<:
end WvfM.D!
我们可以直接写成 %0/qb0N&
set @strSQL = 'select count(*) as Total from [' + @tblName + '] where 1=1 安定 '+ @strWhere ^?sP[;8S!
2、收缩数据库 Q3^h
--重建索引 S^p^)
fAmF
DBCC REINDEX $@]
xi
DBCC INDEXDEFRAG r%iFsV_
--收缩数据和日志 Kz/,V6H:
DBCC SHRINKDB /3SEu(d!
DBCC SHRINKFILE N!wuBRWR
3、压缩数据库 t6mv
dbcc shrinkdatabase(dbname) pnz: <V"Y(
4、转移数据库给新用户以已存在用户权限 :FHEq~4
exec sp_change_users_login 'update_one','newname','oldname' &IzNoB
go w3sU& |N
5、检查备份集 aBG^Xhx
RESTORE VERIFYONLY from disk='E:\dvbbs.bak' hAc|a9 o
6、修复数据库 LW.j)wB]
ALTER DATABASE [dvbbs] SET SINGLE_USER EU|IzUjFj|
GO (S+/e5c)
DBCC CHECKDB('dvbbs',repair_allow_data_loss) WITH TABLOCK ?nbu`K6T
GO kN{$-v=K
ALTER DATABASE [dvbbs] SET MULTI_USER ISK 8t
GO h!|U j
7、日志清除 r<:d+5"
SET NOCOUNT ON uPr!;'J=
DECLARE @LogicalFileName sysname, G `!A#As
@MaxMinutes INT, ;s3\Z^h4kd
@NewSize INT hwL`9.w
USE tablename -- 要操作的数据库名 Z2})n
-
SELECT @LogicalFileName = 'tablename_log', -- 日志文件名 [XDV-6KCE.
@MaxMinutes = 10, -- Limit on time allowed to wrap log. ">3t+A
@NewSize = 1 -- 你想设定的日志文件的大小(M) 1i~q~O,
-- Setup / initialize Z}>F
V~4
DECLARE @OriginalSize int
_(8#
SELECT @OriginalSize = size Yk?q \1
FROM sysfiles B&B:P
WHERE name = @LogicalFileName .s,04xW\
SELECT 'Original Size of ' + db_name() + ' LOG is ' + gt(p%~
CONVERT(VARCHAR(30),@OriginalSize) + ' 8K pages or ' + Do\j _
CONVERT(VARCHAR(30),(@OriginalSize*8/1024)) + 'MB' .Tq8Qdl
FROM sysfiles MusUgBQy
WHERE name = @LogicalFileName :3D6OBkB
CREATE TABLE DummyTrans 7qUg~GJX
(DummyColumn char (8000) not null) DC1.f(cdR
DECLARE @Counter INT, n^l*oEl
@StartTime DATETIME, "a~r'+'<
@TruncLog VARCHAR(255) {,h_T0D^j
SELECT @StartTime = GETDATE(), T|D^kL%m!
@TruncLog = 'BACKUP LOG ' + db_name() + ' WITH TRUNCATE_ONLY' jN*wbqL
DBCC SHRINKFILE (@LogicalFileName, @NewSize) {J,"iJKop
EXEC (@TruncLog) ^0}wmxDq
-- Wrap the log if necessary. jnztCNaX
WHILE @MaxMinutes > DATEDIFF (mi, @StartTime, GETDATE()) -- time has not expired 4:a ~Wlp[
AND @OriginalSize = (SELECT size FROM sysfiles WHERE name = @LogicalFileName) n;kWAYgg
AND (@OriginalSize * 8 /1024) > @NewSize (?^ F }]
BEGIN -- Outer loop. ^p9V5o
SELECT @Counter = 0 FGyrDRDwC
WHILE ((@Counter < @OriginalSize / 16) AND (@Counter < 50000)) -=gI_wLbM
BEGIN -- update %W7%] Z@j
INSERT DummyTrans VALUES ('Fill Log') \z FCph4
DELETE DummyTrans c*E7nc)u
SELECT @Counter = @Counter + 1 ~?fl8RF\
END MD<x{7O12>
EXEC (@TruncLog) n w`rH*
END Y,}h{*9Kd
SELECT 'Final Size of ' + db_name() + ' LOG is ' + cNmAr8^}
CONVERT(VARCHAR(30),size) + ' 8K pages or ' + R13k2jLSQ
CONVERT(VARCHAR(30),(size*8/1024)) + 'MB' JeNX5bXW
FROM sysfiles /}6y\3h
WHERE name = @LogicalFileName wL3RcXW``e
DROP TABLE DummyTrans V?"U)Y@Y
SET NOCOUNT OFF f"*4R
kG
8、说明:更改某个表 (GL'm[V
exec sp_changeobjectowner 'tablename','dbo' SG\ /m'F
9、存储更改全部表 C R?}*
CREATE PROCEDURE dbo.User_ChangeObjectOwnerBatch YLA(hg|
@OldOwner as NVARCHAR(128), wXqwb|2
@NewOwner as NVARCHAR(128) ftPhE)i
AS ^lZ7% 6
DECLARE @Name as NVARCHAR(128) $!9/s S?
DECLARE @Owner as NVARCHAR(128) Z]TQ+9t
DECLARE @OwnerName as NVARCHAR(128) aZ\Z7(
DECLARE curObject CURSOR FOR ^w``(-[*
select 'Name' = name, Vq`/]&
'Owner' = user_name(uid) p=> +3
from sysobjects cl&?'`
)
where user_name(uid)=@OldOwner ~uZ9%UB_m
order by name G;u~H<
OPEN curObject j#P4&
FETCH NEXT FROM curObject INTO @Name, @Owner OAW_c.)5D
WHILE(@@FETCH_STATUS=0) oPa oQbR(A
BEGIN vf<Dqy <M.
if @Owner=@OldOwner rKslgZhQ
begin hrzxc4,W
set @OwnerName = @OldOwner + '.' + rtrim(@Name) >yT1oD0+x
exec sp_changeobjectowner @OwnerName, @NewOwner ^q/^.Gf
end ,P`G IGvkA
-- select @name,@NewOwner,@OldOwner OGJrwl
FETCH NEXT FROM curObject INTO @Name, @Owner L/WRVc6
END iM:-750n/
close curObject G:lhrT{
deallocate curObject ps,Kj3^T<
GO zZRLFfz<9
10、SQL SERVER中直接循环写入数据 tB`"gC~
declare @i int f-[.^/
set @i=1 Ps\4k#aOv
while @i<30 sg}<()
begin ,%xat`d3,3
insert into test (userid) values(@i) N2[j By8M
set @i=@i+1 K3tW Y
4-
end e@Ev']
小记存储过程中经常用到的本周,本月,本年函数 v*JKLA
Dateadd(wk,datediff(wk,0,getdate()),-1) 1(# H%
Dateadd(wk,datediff(wk,0,getdate()),6) ,Fkq/h
Dateadd(mm,datediff(mm,0,getdate()),0) #`%S[)RT
Dateadd(ms,-3,dateadd(mm,datediff(m,0,getdate())+1,0)) A=|a!N/
Dateadd(yy,datediff(yy,0,getdate()),0) tS3&&t
Dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate())+1, 0)) Sw-2vnSdM
上面的SQL代码只是一个时间段 Z>Rshtg
Dateadd(wk,datediff(wk,0,getdate()),-1) <6+B;brh
Dateadd(wk,datediff(wk,0,getdate()),6) *9=}f;~
就是表示本周时间段. CW8YNJ'
下面的SQL的条件部分,就是查询时间段在本周范围内的: AU%Yr6
Where Time BETWEEN Dateadd(wk,datediff(wk,0,getdate()),-1) AND Dateadd(wk,datediff(wk,0,getdate()),6) 5?
Y(FhnIC
而在存储过程中 k$J!,!q
select @begintime = Dateadd(wk,datediff(wk,0,getdate()),-1) /=9dX;
#
select @endtime = Dateadd(wk,datediff(wk,0,getdate()),6) KV&6v`K/N