SQL语句先前写的时候,很容易把一些特殊的用法忘记,我特此整理了一下SQL语句操作。 ]Qx-f*
D6
-M[BC~!0;
X)9|ZF2`
一、基础 o+<hI
1、说明:创建数据库 F
'HYWH0?
CREATE DATABASE database-name 6ESS>I"su
2、说明:删除数据库 )OGO
wStz
drop database dbname &j{IG`Trl
3、说明:备份sql server yAel4b/}
--- 创建 备份数据的 device <lPHeO<^]
USE master )=,;-&AR
EXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1.dat' 6XVJ/qZ
--- 开始 备份 u`*$EP-%
BACKUP DATABASE pubs TO testBack c/3]M>+M
4、说明:创建新表 @(tuE
create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..) <("P5@cExU
根据已有的表创建新表: 3URrK[%x`
A:create table tab_new like tab_old (使用旧表创建新表) 6XeqK*r*
B:create table tab_new as select col1,col2... from tab_old definition only O}lqY?0*
5、说明:删除新表 a9nXh6
drop table tabname 0R,Y[).U
6、说明:增加一个列 sD<8-n
Alter table tabname add column col type rIH+X2x
注:列增加后将不能删除。DB2中列加上后数据类型也不能改变,唯一能改变的是增加varchar类型的长度。 mP)im]H
7、说明:添加主键: Alter table tabname add primary key(col) o`ODz[04
说明:删除主键: Alter table tabname drop primary key(col)
bqR0./V
8、说明:创建索引:create [unique] index idxname on tabname(col....) y=}a55:qE
删除索引:drop index idxname mO\=#Q>
注:索引是不可更改的,想更改必须删除重新建。 a>nV!b\n5
9、说明:创建视图:create view viewname as select statement 9>5]y}.{
删除视图:drop view viewname E|B1h!!\c
10、说明:几个简单的基本的sql语句 'BEM:1)
选择:select * from table1 where 范围 YjG:ECj}
插入:insert into table1(field1,field2) values(value1,value2) T=cb:PD{%
删除:delete from table1 where 范围 nQ'AB~ Do
更新:update table1 set field1=value1 where 范围 !un_JZD
查找:select * from table1 where field1 like '%value1%' ---like的语法很精妙,查资料! pQ+4++7ID
排序:select * from table1 order by field1,field2 [desc] j%*<W> O
总数:select count as totalcount from table1 |:`gjl_Nf
求和:select sum(field1) as sumvalue from table1 RAEiIf!3
平均:select avg(field1) as avgvalue from table1 _P]k6z+
最大:select max(field1) as maxvalue from table1 >Gxu8,_;
最小:select min(field1) as minvalue from table1 @/?$ ZX/e[
pM@0>DVi
:3*0o3C/
Bk1gE((
11、说明:几个高级查询运算词 %5bN@XD
]p~,C*UH0
&T-udgR9
A: UNION 运算符 \6Hu&WHy
UNION 运算符通过组合其他两个结果表(例如 TABLE1 和 TABLE2)并消去表中任何重复行而派生出一个结果表。当 ALL 随 UNION 一起使用时(即 UNION ALL),不消除重复行。两种情况下,派生表的每一行不是来自 TABLE1 就是来自 TABLE2。 4\8k~#
B: EXCEPT 运算符 -Ar 3>d
EXCEPT 运算符通过包括所有在 TABLE1 中但不在 TABLE2 中的行并消除所有重复行而派生出一个结果表。当 ALL 随 EXCEPT 一起使用时 (EXCEPT ALL),不消除重复行。 K<Y-/t
C: INTERSECT 运算符 7Rom#Kl:
INTERSECT 运算符通过只包括 TABLE1 和 TABLE2 中都有的行并消除所有重复行而派生出一个结果表。当 ALL 随 INTERSECT 一起使用时 (INTERSECT ALL),不消除重复行。 _$4vk
注:使用运算词的几个查询结果行必须是一致的。 /E6Tt
12、说明:使用外连接 "{(4
A、left outer join: JE+{Vx}
左外连接(左连接):结果集几包括连接表的匹配行,也包括左连接表的所有行。 RD p(Ci
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 hLLg
B:right outer join: JSiLG0
右外连接(右连接):结果集既包括连接表的匹配连接行,也包括右连接表的所有行。 QGd"Z lQ
C:full outer join: '^M3g-C[Jg
全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录。 b*qC
K<tkNWasQ
8DNGqaH;dt
二、提升 "PPn^{bYm
1、说明:复制表(只复制结构,源表名:a 新表名:b) (Access可用) E)l@uPA'1
法一:select * into b from a where 1<>1 nbz?D_
法二:select top 0 * into b from a Rs%6O|u7
2、说明:拷贝表(拷贝数据,源表名:a 目标表名:b) (Access可用) Wj.
_{
insert into b(a, b, c) select d,e,f from b; ~x}=lK N
3、说明:跨数据库之间表的拷贝(具体数据使用绝对路径) (Access可用) T\Q)"GB
insert into b(a, b, c) select d,e,f from b in '具体数据库' where 条件 8/E?3a_g-
例子:..from b in '"&Server.MapPath(".")&"\data.mdb" &"' where.. F%QVn.
4、说明:子查询(表名1:a 表名2:b) uBC*7Mkm
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) %S4pkFR
5、说明:显示文章、提交人和最后回复时间 -T-h~5
select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b CpICb9w
6、说明:外连接查询(表名1:a 表名2:b) o%tvwv
select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c <El6?ml@
7、说明:在线视图查询(表名1:a ) +hS}msu'
select * from (SELECT a,b,c FROM a) T where t.a > 1; :ITz\m
8、说明:between的用法,between限制查询数据范围时包括了边界值,not between不包括 <)(STo
select * from table1 where time between time1 and time2 xlaBOK a%
select a,b,c, from table1 where a not between 数值1 and 数值2 wXsA-H/`
9、说明:in 的使用方法 QFf lx
select * from table1 where a [not] in ('值1','值2','值4','值6') dPRGL
hWF
10、说明:两张关联表,删除主表中已经在副表中没有的信息 e[8p /hId
delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 ) "^ cn9AG{
11、说明:四表联查问题: j^~WAWbFh
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 ..... %@jv\J
12、说明:日程安排提前五分钟提醒 Iih~rWJ
SQL: select * from 日程安排 where datediff('minute',f开始时间,getdate())>5 ~8EG0F;t
13、说明:一条sql 语句搞定数据库分页 "-TIao#
select top 10 b.* from (select top 20 主键字段,排序字段 from 表名 order by 排序字段 desc) a,表名 b where b.主键字段 = a.主键字段 order by a.排序字段
Eyu?T
14、说明:前10条记录 52#@.Qa
select top 10 * form table1 where 范围 s&$Zgf6Z
15、说明:选择在每一组b值相同的数据中对应的a最大的记录的所有信息(类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等.) aKC3T-
select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b) U(=cGA.$
16、说明:包括所有在 TableA 中但不在 TableB和TableC 中的行并消除所有重复行而派生出一个结果表 -pR1xsG
(select a from tableA ) except (select a from tableB) except (select a from tableC) RyxIJJui
17、说明:随机取出10条数据 1]v.Qu<
select top 10 * from tablename order by newid() U;4:F{3m
18、说明:随机选择记录 rT
~qoA\
select newid() u]ZCYJ>
19、说明:删除重复记录 @[S\ FjI
Delete from tablename where id not in (select max(id) from tablename group by col1,col2,...) c;bp[Y3R
20、说明:列出数据库里所有的表名 dDy9yw%f?
select name from sysobjects where type='U' _,;c2
21、说明:列出表里的所有的 !W8'apG&[
select name from syscolumns where id=object_id('TableName') rf8`|9h"7
22、说明:列示type、vender、pcs字段,以type字段排列,case可以方便地实现多重选择,类似select 中的case。 "sRR:wzQu
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 .yF7{/
显示结果: #.%;U' #O
type vender pcs i5*sG^<$H
电脑 A 1 @hWt.qO3s
电脑 A 1 {j
E}mzi
光盘 B 2 B;':Eaa@
光盘 A 2 R
'/Ilz`
手机 B 3 E7axINca
手机 C 3 ]baO{pJi
23、说明:初始化表table1 u<\/T&S
TRUNCATE TABLE table1 #x&1kHu<
24、说明:选择从10到15的记录 F
3}cVO2bY
select top 5 * from (select top 15 * from table order by id asc) table_别名 order by id desc P{)eZINlE
!T|X/BR
(a1 s~
Z%MP:@z
三、技巧 y)!K@
1、1=1,1=2的使用,在SQL语句组合时用的较多 810u+%fu
"where 1=1" 是表示选择全部 "where 1=2"全部不选, t1.5hsp
如: uV *&a~
if @strWhere !='' #2&_WM!
begin jQ_j#_Vle
set @strSQL = 'select count(*) as Total from [' + @tblName + '] where ' + @strWhere dd>stp
end :\48=>
else !K1[o'o#
begin [>4Ou^=1
set @strSQL = 'select count(*) as Total from [' + @tblName + ']' 1<
;<?
end [HK[{M=v=
我们可以直接写成 #Gs] u
set @strSQL = 'select count(*) as Total from [' + @tblName + '] where 1=1 安定 '+ @strWhere 5"6Y=AuQ6
2、收缩数据库 [:sV;37s
--重建索引 $}7/mS@c
DBCC REINDEX -mG3#88*
DBCC INDEXDEFRAG <D
pi M`
--收缩数据和日志 qV.*sdS>
DBCC SHRINKDB +X0?bVT
DBCC SHRINKFILE i}+K;,Da:8
3、压缩数据库 sL
XQ)Ce
dbcc shrinkdatabase(dbname) 4jj@"*^a
4、转移数据库给新用户以已存在用户权限 k|nv[xY0
exec sp_change_users_login 'update_one','newname','oldname' c ++tk4
go .QzHHW4&0
5、检查备份集 *9((b;Ju
RESTORE VERIFYONLY from disk='E:\dvbbs.bak' Yyby 1
6、修复数据库 N'!a{rF
ALTER DATABASE [dvbbs] SET SINGLE_USER
F\Ex$:%~
GO aDTNr/I
DBCC CHECKDB('dvbbs',repair_allow_data_loss) WITH TABLOCK 3xh~xE
GO 4lE
j/#}
ALTER DATABASE [dvbbs] SET MULTI_USER sUcx;<|BC
GO %X
O97
7、日志清除 .T/\5_Bx
SET NOCOUNT ON vVmoV0kGt
DECLARE @LogicalFileName sysname, =zt@*o{F
@MaxMinutes INT, )avli@W-3j
@NewSize INT ?x"<0k1g
USE tablename -- 要操作的数据库名 ;+`t[ go
SELECT @LogicalFileName = 'tablename_log', -- 日志文件名 z'JtH^^Z
@MaxMinutes = 10, -- Limit on time allowed to wrap log. kA{[k
@NewSize = 1 -- 你想设定的日志文件的大小(M) Uo<d]4p $
-- Setup / initialize +glT5sOk
DECLARE @OriginalSize int G0|j3y9$
SELECT @OriginalSize = size kf>oZ*/
FROM sysfiles a8FC#kfq
WHERE name = @LogicalFileName xf?*fm?m
SELECT 'Original Size of ' + db_name() + ' LOG is ' + Y'`w.+9
CONVERT(VARCHAR(30),@OriginalSize) + ' 8K pages or ' + CYmwT>P+*4
CONVERT(VARCHAR(30),(@OriginalSize*8/1024)) + 'MB' {xp/1?Mo*
FROM sysfiles vZmM=hW ~
WHERE name = @LogicalFileName U|={LU
CREATE TABLE DummyTrans #)2'I`_E
(DummyColumn char (8000) not null) 3VbMW, _&"
DECLARE @Counter INT,
@S yGj#
@StartTime DATETIME, mTT1,|
@TruncLog VARCHAR(255) L\XnTL{
SELECT @StartTime = GETDATE(), /Zap'S/
@TruncLog = 'BACKUP LOG ' + db_name() + ' WITH TRUNCATE_ONLY' 9H$#c_zrq
DBCC SHRINKFILE (@LogicalFileName, @NewSize) oEd+
EXEC (@TruncLog) ?`,<l#sj
-- Wrap the log if necessary. >fPa>[_1
WHILE @MaxMinutes > DATEDIFF (mi, @StartTime, GETDATE()) -- time has not expired 9"KEHf!
AND @OriginalSize = (SELECT size FROM sysfiles WHERE name = @LogicalFileName) +ZEj(fd9
AND (@OriginalSize * 8 /1024) > @NewSize <T+)~&g$
BEGIN -- Outer loop. yf*^Y74
SELECT @Counter = 0 hW6og)x
WHILE ((@Counter < @OriginalSize / 16) AND (@Counter < 50000)) &xo,49`!
BEGIN -- update #HpF\{{v
INSERT DummyTrans VALUES ('Fill Log') |TatRB3>
DELETE DummyTrans )" q$g&
SELECT @Counter = @Counter + 1 [O>}%
END j{U?kW{o
EXEC (@TruncLog) z;JyHC)
END R$IxR=hMx
SELECT 'Final Size of ' + db_name() + ' LOG is ' + '.r_6X$7Jt
CONVERT(VARCHAR(30),size) + ' 8K pages or ' + <spV Up
CONVERT(VARCHAR(30),(size*8/1024)) + 'MB' A'HFpsa
FROM sysfiles L}pMjyM
WHERE name = @LogicalFileName K>hQls+
DROP TABLE DummyTrans //n$#c_}u
SET NOCOUNT OFF {b6| wQ\
8、说明:更改某个表 s4/4o_[W
exec sp_changeobjectowner 'tablename','dbo' :a
@_GIC
9、存储更改全部表 >
L_kSC?
CREATE PROCEDURE dbo.User_ChangeObjectOwnerBatch sa$CCQ
@OldOwner as NVARCHAR(128), 8i/5L=a"`
@NewOwner as NVARCHAR(128) '/%]B@!
AS zgXg-cr
DECLARE @Name as NVARCHAR(128) (`\ DDJ[
DECLARE @Owner as NVARCHAR(128) }lt5!u~}
DECLARE @OwnerName as NVARCHAR(128) GKTt!MK
DECLARE curObject CURSOR FOR 7v3'JG1r-
select 'Name' = name, 1t
wC-rC
'Owner' = user_name(uid) Jd?N5.
from sysobjects kVR_?ch{
where user_name(uid)=@OldOwner `>-fU<Q1
order by name ]-h;gN
OPEN curObject /N.xh
FETCH NEXT FROM curObject INTO @Name, @Owner 82l$]W 4
WHILE(@@FETCH_STATUS=0) lKWe=xY\B
BEGIN u0 myB/`
if @Owner=@OldOwner 9+H C!Uot
begin 2CcUClP$
set @OwnerName = @OldOwner + '.' + rtrim(@Name) gb+iy$o-
exec sp_changeobjectowner @OwnerName, @NewOwner ICAp
end U:"X *
-- select @name,@NewOwner,@OldOwner D])&>
FETCH NEXT FROM curObject INTO @Name, @Owner blO(Th&
END LH/lnrN
close curObject |LhVANz
deallocate curObject {o1vv+i
GO @oE^(
10、SQL SERVER中直接循环写入数据 D1hy:KkAv]
declare @i int .8Eh[yiln
set @i=1 3,`I\>No
while @i<30 vZMb/}-o
begin ;Z^\$v9?
insert into test (userid) values(@i) N~H!6N W
set @i=@i+1 B'}h6ZH
end 9U~fc U6
小记存储过程中经常用到的本周,本月,本年函数 U )kl!
Dateadd(wk,datediff(wk,0,getdate()),-1) >T84NFdz+
Dateadd(wk,datediff(wk,0,getdate()),6) Buc{dcL/
Dateadd(mm,datediff(mm,0,getdate()),0) NULew]:5
Dateadd(ms,-3,dateadd(mm,datediff(m,0,getdate())+1,0)) |i_+b@Lul
Dateadd(yy,datediff(yy,0,getdate()),0) <@:RS$"i
Dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate())+1, 0)) j.=&qYc0"
上面的SQL代码只是一个时间段 h</,p49gM
Dateadd(wk,datediff(wk,0,getdate()),-1) ]R%[cr
Dateadd(wk,datediff(wk,0,getdate()),6) s0r::yO
就是表示本周时间段. Ckd
j|
下面的SQL的条件部分,就是查询时间段在本周范围内的: \LuaI
Where Time BETWEEN Dateadd(wk,datediff(wk,0,getdate()),-1) AND Dateadd(wk,datediff(wk,0,getdate()),6) /LwS|c6}}
而在存储过程中 KU$:p^0l;*
select @begintime = Dateadd(wk,datediff(wk,0,getdate()),-1) tb$I8T
select @endtime = Dateadd(wk,datediff(wk,0,getdate()),6) |wbXu: