SQL语句先前写的时候,很容易把一些特殊的用法忘记,我特此整理了一下SQL语句操作。 k&^f Iz
$8b/"Qm
r'j*f"uAm
一、基础 m$3&r2vgi
1、说明:创建数据库 Pp?J5HW
CREATE DATABASE database-name :Q89j4,
2、说明:删除数据库 UGIyNMY
drop database dbname 3a =KgOvp
3、说明:备份sql server >qOhzbAH{<
--- 创建 备份数据的 device ]P-;]*&=
USE master 9G&l{7 =
EXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1.dat' 3.Y/ZWON
--- 开始 备份 ibh!8" [
BACKUP DATABASE pubs TO testBack SOd(& >
4、说明:创建新表 mwBOhEefNJ
create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..) s iC/k*
根据已有的表创建新表: N[Fz6,ZG _
A:create table tab_new like tab_old (使用旧表创建新表) Av{1~%hU
B:create table tab_new as select col1,col2... from tab_old definition only B?k75G
5、说明:删除新表 A@GyKx%x$
drop table tabname P9gIKOOx#4
6、说明:增加一个列 ' y1=Z
Alter table tabname add column col type b}Jcj
注:列增加后将不能删除。DB2中列加上后数据类型也不能改变,唯一能改变的是增加varchar类型的长度。 2x0[@cTi?
7、说明:添加主键: Alter table tabname add primary key(col) YOqBIbp~&)
说明:删除主键: Alter table tabname drop primary key(col) U:p<pTnMR
8、说明:创建索引:create [unique] index idxname on tabname(col....) ">|fB&~A
删除索引:drop index idxname Xfe,ZC)
注:索引是不可更改的,想更改必须删除重新建。 [W`
_`
9、说明:创建视图:create view viewname as select statement VCtj8hKDr
删除视图:drop view viewname P)4SrqW_
10、说明:几个简单的基本的sql语句 H_Vf_p?
选择:select * from table1 where 范围 )jvYJ9s
插入:insert into table1(field1,field2) values(value1,value2) 2!}5shB
删除:delete from table1 where 范围 )D Y?Y-n
更新:update table1 set field1=value1 where 范围 yy@g=<okt\
查找:select * from table1 where field1 like '%value1%' ---like的语法很精妙,查资料! c&ymVB?G:1
排序:select * from table1 order by field1,field2 [desc] VXQ~PF]z0
总数:select count as totalcount from table1 +eQg+@u
求和:select sum(field1) as sumvalue from table1 ?FJU>+{">
平均:select avg(field1) as avgvalue from table1 jCkYzQUPz
最大:select max(field1) as maxvalue from table1 f/aSqhAW
最小:select min(field1) as minvalue from table1 qh{hpX)\D
ZJ1%
ar }F^8Ku
)V7bi^r
11、说明:几个高级查询运算词 N"Q-xK
um~U_&>
fnl~0
A: UNION 运算符 Eu2@%2}P
UNION 运算符通过组合其他两个结果表(例如 TABLE1 和 TABLE2)并消去表中任何重复行而派生出一个结果表。当 ALL 随 UNION 一起使用时(即 UNION ALL),不消除重复行。两种情况下,派生表的每一行不是来自 TABLE1 就是来自 TABLE2。 A@4sb
W_
B: EXCEPT 运算符 w,n&K6<
EXCEPT 运算符通过包括所有在 TABLE1 中但不在 TABLE2 中的行并消除所有重复行而派生出一个结果表。当 ALL 随 EXCEPT 一起使用时 (EXCEPT ALL),不消除重复行。 Dm2&}{&K
C: INTERSECT 运算符 gm'8,ZL
INTERSECT 运算符通过只包括 TABLE1 和 TABLE2 中都有的行并消除所有重复行而派生出一个结果表。当 ALL 随 INTERSECT 一起使用时 (INTERSECT ALL),不消除重复行。 )cxLpTr
注:使用运算词的几个查询结果行必须是一致的。 F[5[@y
12、说明:使用外连接 < j^8L^
A、left outer join: 1%g%I8W%
左外连接(左连接):结果集几包括连接表的匹配行,也包括左连接表的所有行。 Bu$Z+o
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 hX;JMQ915
B:right outer join: as6a)t.^
右外连接(右连接):结果集既包括连接表的匹配连接行,也包括右连接表的所有行。 %|Sh|\6A!
C:full outer join: s|FfBG
全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录。
A%(t' z
$}+t|`*q8]
二、提升 SHWD@WLE4
1、说明:复制表(只复制结构,源表名:a 新表名:b) (Access可用) YBF|0A{[Y
法一:select * into b from a where 1<>1 F|nJ3:v
法二:select top 0 * into b from a j
S~Wcu
2、说明:拷贝表(拷贝数据,源表名:a 目标表名:b) (Access可用) d.>Zn?u4L
insert into b(a, b, c) select d,e,f from b; &V"9[0
3、说明:跨数据库之间表的拷贝(具体数据使用绝对路径) (Access可用)
$I}7EI
insert into b(a, b, c) select d,e,f from b in '具体数据库' where 条件 VEFUj&t;xW
例子:..from b in '"&Server.MapPath(".")&"\data.mdb" &"' where.. <u`m4w
4、说明:子查询(表名1:a 表名2:b) f_'#wc6
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) {-a8^IK,
5、说明:显示文章、提交人和最后回复时间 },#@q_E
select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b +9yV'd>U
6、说明:外连接查询(表名1:a 表名2:b) <l>o6K
select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c 0q}k"(9
7、说明:在线视图查询(表名1:a ) [ 'aSPA
select * from (SELECT a,b,c FROM a) T where t.a > 1; oQ
YmywY
8、说明:between的用法,between限制查询数据范围时包括了边界值,not between不包括 bMU0h,|]
select * from table1 where time between time1 and time2 S3fyt]pp
select a,b,c, from table1 where a not between 数值1 and 数值2 cug=k
9、说明:in 的使用方法 pT ]: TRPS
select * from table1 where a [not] in ('值1','值2','值4','值6') 8p"R4
10、说明:两张关联表,删除主表中已经在副表中没有的信息 ~&{LMf
delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 ) q#pD}Xe$
11、说明:四表联查问题: *UxN~?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 ..... {zha jY7
12、说明:日程安排提前五分钟提醒 :9?y-X
SQL: select * from 日程安排 where datediff('minute',f开始时间,getdate())>5 3IB||oN$T
13、说明:一条sql 语句搞定数据库分页 Lfr>y_i;F
select top 10 b.* from (select top 20 主键字段,排序字段 from 表名 order by 排序字段 desc) a,表名 b where b.主键字段 = a.主键字段 order by a.排序字段 MbbKo-7F$
14、说明:前10条记录 K-X@3&X}
select top 10 * form table1 where 范围 0*y|k1
15、说明:选择在每一组b值相同的数据中对应的a最大的记录的所有信息(类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等.) nI0TvBD
select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b) +T!7jC(O
Q
16、说明:包括所有在 TableA 中但不在 TableB和TableC 中的行并消除所有重复行而派生出一个结果表 0vYHx V
(select a from tableA ) except (select a from tableB) except (select a from tableC) >oYr=O
17、说明:随机取出10条数据 R-[t4BHn
select top 10 * from tablename order by newid() `%@|sK2
18、说明:随机选择记录 X7."hGu@
select newid() Z~[EZgIg
19、说明:删除重复记录 HdR%n
Delete from tablename where id not in (select max(id) from tablename group by col1,col2,...) p#A{.6Pa:
20、说明:列出数据库里所有的表名 F4:giu ht
select name from sysobjects where type='U' caH!(V}6
21、说明:列出表里的所有的 6O@/Y;5i
select name from syscolumns where id=object_id('TableName') mu$0x)
22、说明:列示type、vender、pcs字段,以type字段排列,case可以方便地实现多重选择,类似select 中的case。 |K(jXZ)
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 CO5>Q o
显示结果: P,RdYM06
type vender pcs a Byetc88/
电脑 A 1 }}s.0Q
电脑 A 1 .S{>?2
光盘 B 2 ]:g;S,{
光盘 A 2 EEI!pi
手机 B 3 $v \@mW*R
手机 C 3 Z23*`yR
23、说明:初始化表table1 X6Wj,a
TRUNCATE TABLE table1 j84g6; 4Dv
24、说明:选择从10到15的记录 n-)Xs;`2
select top 5 * from (select top 15 * from table order by id asc) table_别名 order by id desc 'h*^;3@*
IN!,|)8s
d(t$riFX}
Ec4+wRWk85
三、技巧 !Zi_4 .(4
1、1=1,1=2的使用,在SQL语句组合时用的较多 9*&RvsrX
"where 1=1" 是表示选择全部 "where 1=2"全部不选, Et0[HotO
如: _(zPA4q8q
if @strWhere !='' WAzn`xGxR"
begin F Bk_LEcX
set @strSQL = 'select count(*) as Total from [' + @tblName + '] where ' + @strWhere bf*VY&S-T
end 3*<?'O7I0
else =" Sb>_
begin aM6qYO!jA
set @strSQL = 'select count(*) as Total from [' + @tblName + ']' I[g;p8jr
end o?]N2e&(
我们可以直接写成 0 v>*P*
set @strSQL = 'select count(*) as Total from [' + @tblName + '] where 1=1 安定 '+ @strWhere _&U.DMt2 C
2、收缩数据库 4Rv.m*^ B
--重建索引 9]]isE8r
DBCC REINDEX lKT<aYX
DBCC INDEXDEFRAG u|eV'-R)s
--收缩数据和日志 [OU[i(,{
DBCC SHRINKDB rAwuWM@BIg
DBCC SHRINKFILE !ma%Zk
3、压缩数据库 jMUN|(=Y
dbcc shrinkdatabase(dbname) Tj3xK%K_r3
4、转移数据库给新用户以已存在用户权限 G\4*6iw:
exec sp_change_users_login 'update_one','newname','oldname' ^6kE tTO*
go :d{-"RAG"
5、检查备份集 SSH 1Ge5|
RESTORE VERIFYONLY from disk='E:\dvbbs.bak' m2esVvP
6、修复数据库 &CcUr#|
ALTER DATABASE [dvbbs] SET SINGLE_USER xa&5o`>1G
GO knb 9s`wR
DBCC CHECKDB('dvbbs',repair_allow_data_loss) WITH TABLOCK 1RM@~I$0
GO %K/zVYGm&
ALTER DATABASE [dvbbs] SET MULTI_USER Hsl0|jy(/
GO H5J1j*P<d
7、日志清除 =Ul{#R
z
SET NOCOUNT ON S?BI)shmg
DECLARE @LogicalFileName sysname, umJ!j&(
@MaxMinutes INT, *rH#k?
@NewSize INT e0&x?U*/
USE tablename -- 要操作的数据库名 J&w'0
SELECT @LogicalFileName = 'tablename_log', -- 日志文件名 b>]MZhLJe
@MaxMinutes = 10, -- Limit on time allowed to wrap log. q37d:Hp
@NewSize = 1 -- 你想设定的日志文件的大小(M) [,?5}'we
-- Setup / initialize ekV|a1)
DECLARE @OriginalSize int mYRsM s
SELECT @OriginalSize = size VlbS\Y.
FROM sysfiles d(!g9H
WHERE name = @LogicalFileName A.wuB
SELECT 'Original Size of ' + db_name() + ' LOG is ' + M9ACaf@
CONVERT(VARCHAR(30),@OriginalSize) + ' 8K pages or ' + `"RT(` m
CONVERT(VARCHAR(30),(@OriginalSize*8/1024)) + 'MB' "x~su?KiA
FROM sysfiles b2vCr F;
WHERE name = @LogicalFileName gF53[\w^v
CREATE TABLE DummyTrans :rzq[J^
(DummyColumn char (8000) not null) `SM37({c
DECLARE @Counter INT, QTLGM-Z
@StartTime DATETIME, 6U(MHxY
@TruncLog VARCHAR(255) 0CR~ vQf#r
SELECT @StartTime = GETDATE(), S|pf.l
@TruncLog = 'BACKUP LOG ' + db_name() + ' WITH TRUNCATE_ONLY' bZf}m=C!
DBCC SHRINKFILE (@LogicalFileName, @NewSize) K}a3Bj,
EXEC (@TruncLog) LAjreC<W
-- Wrap the log if necessary. l)K8.(2
WHILE @MaxMinutes > DATEDIFF (mi, @StartTime, GETDATE()) -- time has not expired _|f_%S8a_=
AND @OriginalSize = (SELECT size FROM sysfiles WHERE name = @LogicalFileName) Zog&:]P'F
AND (@OriginalSize * 8 /1024) > @NewSize K|V<e[X[V
BEGIN -- Outer loop. `E:&a]ul
SELECT @Counter = 0 mnm7{?#[
WHILE ((@Counter < @OriginalSize / 16) AND (@Counter < 50000)) {[:]}m(c
BEGIN -- update h*B7UzCg
INSERT DummyTrans VALUES ('Fill Log') 45aFH}w:
DELETE DummyTrans ,
aJC7'(
SELECT @Counter = @Counter + 1 zbgH}6b
END V*j1[d
EXEC (@TruncLog) p"tCMB
END S!6 ? b5
SELECT 'Final Size of ' + db_name() + ' LOG is ' + )Rc
CONVERT(VARCHAR(30),size) + ' 8K pages or ' + z;Yo76P
CONVERT(VARCHAR(30),(size*8/1024)) + 'MB' ]9hXiY
FROM sysfiles {({Rb$
WHERE name = @LogicalFileName HD!2|b~@
DROP TABLE DummyTrans }O+`X) 9
SET NOCOUNT OFF G:4'')T
8、说明:更改某个表 9YEE.=]T
exec sp_changeobjectowner 'tablename','dbo' yBkcYHT
9、存储更改全部表 \m%Z;xKG
CREATE PROCEDURE dbo.User_ChangeObjectOwnerBatch kK%@cIXS3
@OldOwner as NVARCHAR(128), w0&|8y
@NewOwner as NVARCHAR(128) uWDWf5@
AS (U([T -H
DECLARE @Name as NVARCHAR(128) PFI^+';
DECLARE @Owner as NVARCHAR(128) H84Zg/ ^
DECLARE @OwnerName as NVARCHAR(128) PTP0 _|K
DECLARE curObject CURSOR FOR 3{H&{@Q
select 'Name' = name, i#KY'"P
'Owner' = user_name(uid) GAU7w"sE
from sysobjects c0f8*O4i
where user_name(uid)=@OldOwner 5H}d\=z
order by name ,R[<+!RS
OPEN curObject %v)+]Ds{
FETCH NEXT FROM curObject INTO @Name, @Owner /K :H2?J
WHILE(@@FETCH_STATUS=0) iT=h}>
BEGIN WGA"e
if @Owner=@OldOwner =<[M$"S7d6
begin 7 0Wy]8<P
set @OwnerName = @OldOwner + '.' + rtrim(@Name) TR'<D9kn
exec sp_changeobjectowner @OwnerName, @NewOwner '4)4* 3z,
end ]6;G#
-- select @name,@NewOwner,@OldOwner
PM^Xh*~
FETCH NEXT FROM curObject INTO @Name, @Owner 4Hq6nT/
END <Gj]XAoe%
close curObject 99*QfC
deallocate curObject Rc(E';uc
GO R/P9 =yvg0
10、SQL SERVER中直接循环写入数据 8SOfX^;o
declare @i int 7bL48W<QD
set @i=1 OLE@35"v]
while @i<30 ge|Cvv
begin CF]#0*MI
insert into test (userid) values(@i) FV\$M6
_
set @i=@i+1 )^7- qy
end 3(3-#MD0
小记存储过程中经常用到的本周,本月,本年函数 F0KNkL>&g
Dateadd(wk,datediff(wk,0,getdate()),-1) 8d[!"lL
Dateadd(wk,datediff(wk,0,getdate()),6) }WnoI2
Dateadd(mm,datediff(mm,0,getdate()),0) g`I$U%a_2
Dateadd(ms,-3,dateadd(mm,datediff(m,0,getdate())+1,0)) KvmXRf*z
Dateadd(yy,datediff(yy,0,getdate()),0) 6yK"g7
Dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate())+1, 0)) i?n#ge
上面的SQL代码只是一个时间段 ZN}U^9m=
Dateadd(wk,datediff(wk,0,getdate()),-1) {nH*Wu*^
Dateadd(wk,datediff(wk,0,getdate()),6) jwO7r0?\`G
就是表示本周时间段. Lm7fz9F%
下面的SQL的条件部分,就是查询时间段在本周范围内的: M9Qx F
Where Time BETWEEN Dateadd(wk,datediff(wk,0,getdate()),-1) AND Dateadd(wk,datediff(wk,0,getdate()),6) s)}EMDY
而在存储过程中 ?7dV:]%~2
select @begintime = Dateadd(wk,datediff(wk,0,getdate()),-1) &uXu$)IZ
select @endtime = Dateadd(wk,datediff(wk,0,getdate()),6) ,
%A2wV