SQL语句先前写的时候,很容易把一些特殊的用法忘记,我特此整理了一下SQL语句操作。 vKnZ= =B
]a.e;c-
&M5v EPR
一、基础 ,l AZ4
1、说明:创建数据库 &wU"6E
CREATE DATABASE database-name (!@gm)#h
2、说明:删除数据库 ^}2!fRKAmo
drop database dbname T7i>aM$+
3、说明:备份sql server "3jTU
--- 创建 备份数据的 device Ngx2N<$<*g
USE master qy?$t:*pp
EXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1.dat' f'ld6jt|%
--- 开始 备份 $|Ol?s
BACKUP DATABASE pubs TO testBack Wj3i*x$
4、说明:创建新表 ag8)^p'9
create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..) #SHJ0+)o
根据已有的表创建新表: KiG19R$
A:create table tab_new like tab_old (使用旧表创建新表) %_n%-Qn
B:create table tab_new as select col1,col2... from tab_old definition only #3ZAMV
5、说明:删除新表 sh,4n{+
drop table tabname vg?(0Gasm*
6、说明:增加一个列 kt`ln
Alter table tabname add column col type tWl')^
注:列增加后将不能删除。DB2中列加上后数据类型也不能改变,唯一能改变的是增加varchar类型的长度。 W`LG.`JW
7、说明:添加主键: Alter table tabname add primary key(col) \="U|LzG
说明:删除主键: Alter table tabname drop primary key(col) :BR_%$
8、说明:创建索引:create [unique] index idxname on tabname(col....) ^%%Rf
删除索引:drop index idxname "&XhMw4
注:索引是不可更改的,想更改必须删除重新建。 (8~mf$ zx,
9、说明:创建视图:create view viewname as select statement V* JqC
删除视图:drop view viewname #5y+gdN
10、说明:几个简单的基本的sql语句 %npLgCF
选择:select * from table1 where 范围 3W ]zLUn
插入:insert into table1(field1,field2) values(value1,value2) JkR%o
#>5
删除:delete from table1 where 范围 yU(}1ZID
更新:update table1 set field1=value1 where 范围 1
39T*0C
查找:select * from table1 where field1 like '%value1%' ---like的语法很精妙,查资料! C:&Sk\
排序:select * from table1 order by field1,field2 [desc] e`a4Gr
总数:select count as totalcount from table1 CUdpT$ $x3
求和:select sum(field1) as sumvalue from table1 kqZRg>1A
平均:select avg(field1) as avgvalue from table1 f3,LX]zKA
最大:select max(field1) as maxvalue from table1 !m=Js"
最小:select min(field1) as minvalue from table1 GYy8kp84
3,Z;J5VL4!
,c&t#mu*0
K_t >T)K
11、说明:几个高级查询运算词 B]hRYU
r]}6iF.
s`Z.H5V>\
A: UNION 运算符 g_PP9S_?
UNION 运算符通过组合其他两个结果表(例如 TABLE1 和 TABLE2)并消去表中任何重复行而派生出一个结果表。当 ALL 随 UNION 一起使用时(即 UNION ALL),不消除重复行。两种情况下,派生表的每一行不是来自 TABLE1 就是来自 TABLE2。 [V
/f{y~{
B: EXCEPT 运算符 |j/Y#.k;{0
EXCEPT 运算符通过包括所有在 TABLE1 中但不在 TABLE2 中的行并消除所有重复行而派生出一个结果表。当 ALL 随 EXCEPT 一起使用时 (EXCEPT ALL),不消除重复行。 +5-|6
C: INTERSECT 运算符 6f0o'
INTERSECT 运算符通过只包括 TABLE1 和 TABLE2 中都有的行并消除所有重复行而派生出一个结果表。当 ALL 随 INTERSECT 一起使用时 (INTERSECT ALL),不消除重复行。 >8{{H"$;(
注:使用运算词的几个查询结果行必须是一致的。 bCTN^
12、说明:使用外连接 3P75:v
A、left outer join: X:f5t` ;
左外连接(左连接):结果集几包括连接表的匹配行,也包括左连接表的所有行。 %d-WQwJ
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 (-1{W^(
B:right outer join: 1fJ~Wp @1
右外连接(右连接):结果集既包括连接表的匹配连接行,也包括右连接表的所有行。 5`}za-
C:full outer join: Ymnh%wS
全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录。 TUGD!b{
82)=#ye_P
X ?ZLmP7|
二、提升 US's`Ehx
1、说明:复制表(只复制结构,源表名:a 新表名:b) (Access可用) * >2FcoN;
法一:select * into b from a where 1<>1 _lT'nFe=Q
法二:select top 0 * into b from a X%99@ qv
2、说明:拷贝表(拷贝数据,源表名:a 目标表名:b) (Access可用) "IpbR
insert into b(a, b, c) select d,e,f from b; *E>R1bJ8
3、说明:跨数据库之间表的拷贝(具体数据使用绝对路径) (Access可用) g>7i2
insert into b(a, b, c) select d,e,f from b in '具体数据库' where 条件 "tOm
例子:..from b in '"&Server.MapPath(".")&"\data.mdb" &"' where.. D@5h$m5
4、说明:子查询(表名1:a 表名2:b) ]p4?nT@]
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) 8)s0$64Ra
5、说明:显示文章、提交人和最后回复时间 $AZ=;iP-
select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b g;q.vHvsc"
6、说明:外连接查询(表名1:a 表名2:b) 'lEIwJV$
select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c /EHO(d!<
7、说明:在线视图查询(表名1:a ) T.QJ#vKO0
select * from (SELECT a,b,c FROM a) T where t.a > 1; $\k)Y(&
8、说明:between的用法,between限制查询数据范围时包括了边界值,not between不包括 S^i8VYK,C5
select * from table1 where time between time1 and time2 K5<2jl3S
select a,b,c, from table1 where a not between 数值1 and 数值2 it>Bf;
9、说明:in 的使用方法 dA2@PKK
select * from table1 where a [not] in ('值1','值2','值4','值6') >X[:(m'
10、说明:两张关联表,删除主表中已经在副表中没有的信息 7[L%j;)bw
delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 ) iBWEZw)
11、说明:四表联查问题: ME)='~E
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 ..... W! |_ hL
12、说明:日程安排提前五分钟提醒 Bn.R,B0PL
SQL: select * from 日程安排 where datediff('minute',f开始时间,getdate())>5 E@Ewx;P5
13、说明:一条sql 语句搞定数据库分页 !z:j-gT3
select top 10 b.* from (select top 20 主键字段,排序字段 from 表名 order by 排序字段 desc) a,表名 b where b.主键字段 = a.主键字段 order by a.排序字段 B4zuWCE@
14、说明:前10条记录 5KTFf6Uq
select top 10 * form table1 where 范围 #5^OO ou|
15、说明:选择在每一组b值相同的数据中对应的a最大的记录的所有信息(类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等.) fQ.S ,lMe
select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b) &eO.h%@
16、说明:包括所有在 TableA 中但不在 TableB和TableC 中的行并消除所有重复行而派生出一个结果表 ^G5 fs'd
(select a from tableA ) except (select a from tableB) except (select a from tableC) qUg/mdv&
17、说明:随机取出10条数据 EKw)\T1
select top 10 * from tablename order by newid() aWvC-vZk
18、说明:随机选择记录 zLxuxf~4@
select newid() a>6M{C@pd
19、说明:删除重复记录 cN2Pl%7
Delete from tablename where id not in (select max(id) from tablename group by col1,col2,...) n Jz* }=
20、说明:列出数据库里所有的表名 uHZjpMoM
select name from sysobjects where type='U' ~U ]%>Zf
21、说明:列出表里的所有的 ]A+t@/k
select name from syscolumns where id=object_id('TableName') SEu:31k{o
22、说明:列示type、vender、pcs字段,以type字段排列,case可以方便地实现多重选择,类似select 中的case。 SN}3
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 Xrc{wDn
显示结果: wT3D9N.
type vender pcs S,'ekWVD
电脑 A 1 K0@bh/i/^
电脑 A 1 :YLYCVi|
光盘 B 2 GsD?Z%t~%
光盘 A 2 @QYCoEU8J
手机 B 3 P3a]*> .,
手机 C 3 tmeg=U7
23、说明:初始化表table1 3fE0cVG*
TRUNCATE TABLE table1 u#V;
24、说明:选择从10到15的记录 gH"aMEC
select top 5 * from (select top 15 * from table order by id asc) table_别名 order by id desc @.dM1DN)
}lq$Fi/
ojJua c4
+,T}x+D
三、技巧
31]Vo;D
1、1=1,1=2的使用,在SQL语句组合时用的较多 P $r!u%W
"where 1=1" 是表示选择全部 "where 1=2"全部不选, J!Rqm!)q
如: VVuNU"-
if @strWhere !='' xvWP^Qkb
begin ,WoB)V.{(
set @strSQL = 'select count(*) as Total from [' + @tblName + '] where ' + @strWhere Y_XRf8Sw
end jrm^n_6};
else R(}!gv}s
begin ; d}n89DXj
set @strSQL = 'select count(*) as Total from [' + @tblName + ']' %X\Rfn0J"
end A-^B?E
我们可以直接写成 _? $')P|
set @strSQL = 'select count(*) as Total from [' + @tblName + '] where 1=1 安定 '+ @strWhere a@? Bv
2、收缩数据库 h9nh9a(2
--重建索引 hA`9[58/
DBCC REINDEX gxVJH'[V5
DBCC INDEXDEFRAG ^Y8G}Z|
--收缩数据和日志 )"00fZL
DBCC SHRINKDB y#O/Xw
DBCC SHRINKFILE r$LU$F
3、压缩数据库 ^R+CkF4l l
dbcc shrinkdatabase(dbname) ZxDh!_[s
4、转移数据库给新用户以已存在用户权限 {=Py|N\\t
exec sp_change_users_login 'update_one','newname','oldname' pUgas?e&
go q #8z%/~k
5、检查备份集 !:_krLB<
RESTORE VERIFYONLY from disk='E:\dvbbs.bak' !l9#a{#6l
6、修复数据库
~ihi!u%~}
ALTER DATABASE [dvbbs] SET SINGLE_USER XNBzA3W
GO #
?u
bvSdU
DBCC CHECKDB('dvbbs',repair_allow_data_loss) WITH TABLOCK ?]}=4
GO o
7V&HJ[
ALTER DATABASE [dvbbs] SET MULTI_USER 5["n] i
GO Z]OX6G
7、日志清除 0h('@Hb.K#
SET NOCOUNT ON lZ,$lZg9Z
DECLARE @LogicalFileName sysname, y7z ,I
@MaxMinutes INT, MGo`j:0
@NewSize INT 0zjGL7
USE tablename -- 要操作的数据库名 R^K:hKQ
SELECT @LogicalFileName = 'tablename_log', -- 日志文件名 UyMlk
@MaxMinutes = 10, -- Limit on time allowed to wrap log. X`]>J5
@NewSize = 1 -- 你想设定的日志文件的大小(M) zHW&i~
-- Setup / initialize )_l(WF.
DECLARE @OriginalSize int |c2;`T#`o
SELECT @OriginalSize = size e.|t12)L "
FROM sysfiles `K2vG`c
WHERE name = @LogicalFileName 8nSw7:z
SELECT 'Original Size of ' + db_name() + ' LOG is ' + z-nV!#
CONVERT(VARCHAR(30),@OriginalSize) + ' 8K pages or ' + /DSy/p0%
CONVERT(VARCHAR(30),(@OriginalSize*8/1024)) + 'MB' JgldC[|7
FROM sysfiles +J !1z
WHERE name = @LogicalFileName D6P/39}W
CREATE TABLE DummyTrans Z~"8C Kz
(DummyColumn char (8000) not null) 7z8
DECLARE @Counter INT, 7#g<fh
@StartTime DATETIME, O-+!KXHd[
@TruncLog VARCHAR(255) pTYV@5|
SELECT @StartTime = GETDATE(), Q0""wRq'
@TruncLog = 'BACKUP LOG ' + db_name() + ' WITH TRUNCATE_ONLY' 2bpFQ8q
DBCC SHRINKFILE (@LogicalFileName, @NewSize) 7.
eiM!7g
EXEC (@TruncLog) S.owVMQ
-- Wrap the log if necessary. <FvljKuq+
WHILE @MaxMinutes > DATEDIFF (mi, @StartTime, GETDATE()) -- time has not expired *MN("<A_
AND @OriginalSize = (SELECT size FROM sysfiles WHERE name = @LogicalFileName) t\ 9Y)d
AND (@OriginalSize * 8 /1024) > @NewSize }sfvzw_
BEGIN -- Outer loop. M
!rw!,g
SELECT @Counter = 0 XfwH1n/o#
WHILE ((@Counter < @OriginalSize / 16) AND (@Counter < 50000)) (8GA;:G7G
BEGIN -- update &([Gc+"5E.
INSERT DummyTrans VALUES ('Fill Log') wY7+E/
DELETE DummyTrans R1:7]z0B
SELECT @Counter = @Counter + 1 DEenvS`,P
END y$?O0S%F
EXEC (@TruncLog) t3.I ` Z
END i32S(3se
SELECT 'Final Size of ' + db_name() + ' LOG is ' + J]&nZud`
CONVERT(VARCHAR(30),size) + ' 8K pages or ' + 2u}ns8wn
CONVERT(VARCHAR(30),(size*8/1024)) + 'MB' ^coj ETOv
FROM sysfiles /5:qS\Zl
WHERE name = @LogicalFileName @])}+4D(S
DROP TABLE DummyTrans 35SL*zS@-
SET NOCOUNT OFF z|N*Gs>,
8、说明:更改某个表 CDFkH
exec sp_changeobjectowner 'tablename','dbo' p?+;[!:
9、存储更改全部表 }An;)!>(nF
CREATE PROCEDURE dbo.User_ChangeObjectOwnerBatch Olq`mlsK
@OldOwner as NVARCHAR(128), liH1r1M
@NewOwner as NVARCHAR(128) p/jAr+XM
AS 9Cw !<
DECLARE @Name as NVARCHAR(128) v/G^yZa
DECLARE @Owner as NVARCHAR(128) ?? Dv\yLZI
DECLARE @OwnerName as NVARCHAR(128) Ozc9y y!%
DECLARE curObject CURSOR FOR ze#ncnMo
select 'Name' = name, M`@Es#s
'Owner' = user_name(uid) V8z*mnD
from sysobjects `?vI_>md'!
where user_name(uid)=@OldOwner mP ^*nB@,
order by name I,?!NzB
OPEN curObject ?)"v~vs
FETCH NEXT FROM curObject INTO @Name, @Owner n,|YJ,v[
WHILE(@@FETCH_STATUS=0) /_/Z/D!
BEGIN Hd~fSXFl
if @Owner=@OldOwner <V4"+5cJ8
begin ^|%7}=e
set @OwnerName = @OldOwner + '.' + rtrim(@Name) #r80FVwiD
exec sp_changeobjectowner @OwnerName, @NewOwner toC|vn&P
end .J9\Fr@
-- select @name,@NewOwner,@OldOwner 8"x\kSMb
FETCH NEXT FROM curObject INTO @Name, @Owner h,2?+}Fn
END 1.z !u%2
close curObject Qkg([q4
deallocate curObject d/Fy0=0
GO )$E'2|Gm/
10、SQL SERVER中直接循环写入数据 xh!aB6m8R
declare @i int L(kW]
set @i=1 cN#f$
while @i<30 9B1bq #
begin x/#.%Ga#T
insert into test (userid) values(@i) !Ka~X!+\
set @i=@i+1 #0/^v*
end \'Ca%j
小记存储过程中经常用到的本周,本月,本年函数 R&1xZFj
Dateadd(wk,datediff(wk,0,getdate()),-1) 2rX}A3%9^^
Dateadd(wk,datediff(wk,0,getdate()),6) /d1V&Lj
Dateadd(mm,datediff(mm,0,getdate()),0) _."X# }W
Dateadd(ms,-3,dateadd(mm,datediff(m,0,getdate())+1,0)) V4x6,*)e
Dateadd(yy,datediff(yy,0,getdate()),0) ut9R]01:
Dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate())+1, 0)) o(Ro/U(Wu
上面的SQL代码只是一个时间段 Sy34doAZ
Dateadd(wk,datediff(wk,0,getdate()),-1) [E/^bM+
Dateadd(wk,datediff(wk,0,getdate()),6) F#\+.inO
就是表示本周时间段.
B*Q
下面的SQL的条件部分,就是查询时间段在本周范围内的: C=PV-Ul+
Where Time BETWEEN Dateadd(wk,datediff(wk,0,getdate()),-1) AND Dateadd(wk,datediff(wk,0,getdate()),6) iM s(Ywak]
而在存储过程中 +P"u1q*+p
select @begintime = Dateadd(wk,datediff(wk,0,getdate()),-1) e\i}@]
select @endtime = Dateadd(wk,datediff(wk,0,getdate()),6) U\", !S~<