SQL语句先前写的时候,很容易把一些特殊的用法忘记,我特此整理了一下SQL语句操作。 d+0= a]
@ @(O##(7
EyBTja(4
一、基础 [?$tu%Q(Z
1、说明:创建数据库 <KoOJMx(
CREATE DATABASE database-name %ca` v;].
2、说明:删除数据库 z|(<Co8#.
drop database dbname !>kg:xV
3、说明:备份sql server `v2Xp3o4f
--- 创建 备份数据的 device ) <w`:wD
USE master wMCgLh\wi
EXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1.dat' "zqa:D26
--- 开始 备份
BACKUP DATABASE pubs TO testBack K(Tej W#
4、说明:创建新表 p^ OHLT
create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..) )%8st'
根据已有的表创建新表: ?@6Zv$vZ
A:create table tab_new like tab_old (使用旧表创建新表) |S:erYE,G
B:create table tab_new as select col1,col2... from tab_old definition only GE !p
5、说明:删除新表 "Rtt~["%
drop table tabname 0&tr3!h\
6、说明:增加一个列 $) qL=kR
Alter table tabname add column col type lWP]}Uy=5~
注:列增加后将不能删除。DB2中列加上后数据类型也不能改变,唯一能改变的是增加varchar类型的长度。 Z:2%gU&W
7、说明:添加主键: Alter table tabname add primary key(col) hyhm{RC?[
说明:删除主键: Alter table tabname drop primary key(col) ETdN<}m
8、说明:创建索引:create [unique] index idxname on tabname(col....) zzd PR}VG
删除索引:drop index idxname s<3M_mt
注:索引是不可更改的,想更改必须删除重新建。 Np$ue
}yr
9、说明:创建视图:create view viewname as select statement z('t#J!b
删除视图:drop view viewname x>T+k8[n
10、说明:几个简单的基本的sql语句 K<pZ*l
选择:select * from table1 where 范围 S{{wcH$n'i
插入:insert into table1(field1,field2) values(value1,value2) X7tBpyi
删除:delete from table1 where 范围 4#ikdjB;
更新:update table1 set field1=value1 where 范围 rcH{"\F_/
查找:select * from table1 where field1 like '%value1%' ---like的语法很精妙,查资料! g!cW`B'
排序:select * from table1 order by field1,field2 [desc] .%M80X{5~
总数:select count as totalcount from table1 %<U0
求和:select sum(field1) as sumvalue from table1 KYz@H#M
平均:select avg(field1) as avgvalue from table1 j;-2)ZLm
最大:select max(field1) as maxvalue from table1 @V^5_K
最小:select min(field1) as minvalue from table1 q:vGG K^
wk1/&
>CHb;*U
3'SN0VL
11、说明:几个高级查询运算词 !>GDp >0
z 8#{=e
Ip *8R]W
A: UNION 运算符 i#*lK7
UNION 运算符通过组合其他两个结果表(例如 TABLE1 和 TABLE2)并消去表中任何重复行而派生出一个结果表。当 ALL 随 UNION 一起使用时(即 UNION ALL),不消除重复行。两种情况下,派生表的每一行不是来自 TABLE1 就是来自 TABLE2。 pP#|: %
B: EXCEPT 运算符 i4M%{]G3Y
EXCEPT 运算符通过包括所有在 TABLE1 中但不在 TABLE2 中的行并消除所有重复行而派生出一个结果表。当 ALL 随 EXCEPT 一起使用时 (EXCEPT ALL),不消除重复行。 W?[
C
au-
C: INTERSECT 运算符 .VohW=D3
INTERSECT 运算符通过只包括 TABLE1 和 TABLE2 中都有的行并消除所有重复行而派生出一个结果表。当 ALL 随 INTERSECT 一起使用时 (INTERSECT ALL),不消除重复行。 s; sr(34
注:使用运算词的几个查询结果行必须是一致的。 -q&,7'V
12、说明:使用外连接 #GUD^#Jh
A、left outer join: \pP1k.~UnC
左外连接(左连接):结果集几包括连接表的匹配行,也包括左连接表的所有行。 :H:+XIgoR
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 ogJ';i/o
B:right outer join: "x
3C3Zu.;
右外连接(右连接):结果集既包括连接表的匹配连接行,也包括右连接表的所有行。 (io[O?te
C:full outer join: 2|NQ5OA0
全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录。 \zOsq5}
;w._/
~4mRm!DP
二、提升 kN 0N18E
1、说明:复制表(只复制结构,源表名:a 新表名:b) (Access可用) u0qTP]
法一:select * into b from a where 1<>1 'rVB2
`z-
法二:select top 0 * into b from a X `F>kp1
2、说明:拷贝表(拷贝数据,源表名:a 目标表名:b) (Access可用) :EH>&vm
insert into b(a, b, c) select d,e,f from b; K;>9K'n
3、说明:跨数据库之间表的拷贝(具体数据使用绝对路径) (Access可用) 19%zcYTe
insert into b(a, b, c) select d,e,f from b in '具体数据库' where 条件 DV)NY!
例子:..from b in '"&Server.MapPath(".")&"\data.mdb" &"' where.. `v'yGsIV
4、说明:子查询(表名1:a 表名2:b) n_wF_K\h
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) _c(h{dn
5、说明:显示文章、提交人和最后回复时间 ,v?FR
}v
select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b 0}'/3Q
6、说明:外连接查询(表名1:a 表名2:b) b%0@nu4
select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c +Z]}ce
u"
7、说明:在线视图查询(表名1:a ) :z%Zur+n c
select * from (SELECT a,b,c FROM a) T where t.a > 1; Kb'4W-&u!
8、说明:between的用法,between限制查询数据范围时包括了边界值,not between不包括 $-s8tc(
select * from table1 where time between time1 and time2 7Rc>LI*
'
select a,b,c, from table1 where a not between 数值1 and 数值2 vTL/% SJ8
9、说明:in 的使用方法 QC6QqcOX
select * from table1 where a [not] in ('值1','值2','值4','值6') {]dvzoE]
10、说明:两张关联表,删除主表中已经在副表中没有的信息 :%+9y @%
delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 ) |C0!mU
11、说明:四表联查问题: :Smyk.B2!
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 ..... [*5hx_4%B
12、说明:日程安排提前五分钟提醒 cxx8I
SQL: select * from 日程安排 where datediff('minute',f开始时间,getdate())>5 t%@u)b p
13、说明:一条sql 语句搞定数据库分页 /Kd'!lMuz
select top 10 b.* from (select top 20 主键字段,排序字段 from 表名 order by 排序字段 desc) a,表名 b where b.主键字段 = a.主键字段 order by a.排序字段 %:sP #BQM
14、说明:前10条记录 !JVv`YN
select top 10 * form table1 where 范围 S@TfZ3Go|
15、说明:选择在每一组b值相同的数据中对应的a最大的记录的所有信息(类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等.) ['3E'q,4&
select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b) Z&7Yl(|
16、说明:包括所有在 TableA 中但不在 TableB和TableC 中的行并消除所有重复行而派生出一个结果表 }j!C+i
(select a from tableA ) except (select a from tableB) except (select a from tableC) B$7Cjv
17、说明:随机取出10条数据 +6^hp-G7
select top 10 * from tablename order by newid() +x~p&,w?
18、说明:随机选择记录 >\3N#S"PF
select newid() R0bgt2J
19、说明:删除重复记录 H. o3d/8:
Delete from tablename where id not in (select max(id) from tablename group by col1,col2,...) 7loWqZ
20、说明:列出数据库里所有的表名 U r8JG&,
select name from sysobjects where type='U' CBz=-Xr
21、说明:列出表里的所有的 E!>MJlA:k6
select name from syscolumns where id=object_id('TableName') 8m#y>`
22、说明:列示type、vender、pcs字段,以type字段排列,case可以方便地实现多重选择,类似select 中的case。 Z>dvth
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 _lC0XDZ
显示结果: c6iFha;db
type vender pcs Ylgr]?Db*
电脑 A 1 itcM-?
电脑 A 1 *?>52 -&b
光盘 B 2 BJ5^-|
光盘 A 2 "I @akM$x
手机 B 3 xqauSW
手机 C 3 j(M.7Z7^
23、说明:初始化表table1 Qo*OC 9E`
TRUNCATE TABLE table1 :?>yi7w
24、说明:选择从10到15的记录 st >%U9
select top 5 * from (select top 15 * from table order by id asc) table_别名 order by id desc E?VOst&
42:,*4t(
H29vuGQjq
FV/lBWiQQ
三、技巧 mcs!A/]<
1、1=1,1=2的使用,在SQL语句组合时用的较多 2(P<TP._E
"where 1=1" 是表示选择全部 "where 1=2"全部不选,
!FvL2L
如: J0o,ZH9
if @strWhere !='' 9V;A+d,
begin Jyp7+M]
set @strSQL = 'select count(*) as Total from [' + @tblName + '] where ' + @strWhere 8x 8nQ*_
end t@iw&>8z
else =4OV
}z=I
begin l7Wdbx5x0
set @strSQL = 'select count(*) as Total from [' + @tblName + ']'
1DN
end 0W~1v
我们可以直接写成 D8{f7{nY
set @strSQL = 'select count(*) as Total from [' + @tblName + '] where 1=1 安定 '+ @strWhere lg{M\
+
2、收缩数据库 gf^y3F[\
--重建索引 Lzx/9PPYn
DBCC REINDEX NS "1zR+
DBCC INDEXDEFRAG "#h/sAIs
--收缩数据和日志 }*vE/W
DBCC SHRINKDB Hr \vu`p$
DBCC SHRINKFILE 7Jpq7;
3、压缩数据库 K
28s<i`
dbcc shrinkdatabase(dbname) aPX'CG4m
4、转移数据库给新用户以已存在用户权限 UlPGB2B
exec sp_change_users_login 'update_one','newname','oldname' <@y(ikp>
go $8Z4jo
5、检查备份集 U}l=1B
RESTORE VERIFYONLY from disk='E:\dvbbs.bak' Sae*VvT6
6、修复数据库 n8FIxl&u
ALTER DATABASE [dvbbs] SET SINGLE_USER 4.>y[_vu
GO iT+t
DBCC CHECKDB('dvbbs',repair_allow_data_loss) WITH TABLOCK CX;
m8
GO (^]3l%Ed
ALTER DATABASE [dvbbs] SET MULTI_USER n-1
GO ucJ8l(?Qc
7、日志清除 1k{H,p7
SET NOCOUNT ON S$a.8Xh
DECLARE @LogicalFileName sysname, Fw^^sB
@MaxMinutes INT, gj&5>brP
@NewSize INT mqY=N~/O
USE tablename -- 要操作的数据库名 cs4IO
O$
SELECT @LogicalFileName = 'tablename_log', -- 日志文件名 *9`k$'
@MaxMinutes = 10, -- Limit on time allowed to wrap log. 3@1$y`SN
@NewSize = 1 -- 你想设定的日志文件的大小(M) Ml)<4@
-- Setup / initialize '}q/;}ih
DECLARE @OriginalSize int H)Z$j&S{
SELECT @OriginalSize = size V5 Gy|X
FROM sysfiles g+xcKfN{
WHERE name = @LogicalFileName t&IWKu#
SELECT 'Original Size of ' + db_name() + ' LOG is ' + ~RV9'v4
CONVERT(VARCHAR(30),@OriginalSize) + ' 8K pages or ' + th5UzpB4
CONVERT(VARCHAR(30),(@OriginalSize*8/1024)) + 'MB' }|RL6p-/'
FROM sysfiles q77Iq0VR
WHERE name = @LogicalFileName zXxA"
CREATE TABLE DummyTrans SjcX|=S
(DummyColumn char (8000) not null) z$VVt?K
DECLARE @Counter INT, KYq<n& s
@StartTime DATETIME, iaQFVROu
@TruncLog VARCHAR(255) l>("L9
SELECT @StartTime = GETDATE(), \[/}Cy
@TruncLog = 'BACKUP LOG ' + db_name() + ' WITH TRUNCATE_ONLY' Q v},X~^R
DBCC SHRINKFILE (@LogicalFileName, @NewSize) ;)ERxMun
EXEC (@TruncLog) E_{P^7Z|Jg
-- Wrap the log if necessary. <1`MjP*w
WHILE @MaxMinutes > DATEDIFF (mi, @StartTime, GETDATE()) -- time has not expired v7@*dg
AND @OriginalSize = (SELECT size FROM sysfiles WHERE name = @LogicalFileName) B|=S-5pv*
AND (@OriginalSize * 8 /1024) > @NewSize
8L`wib2
BEGIN -- Outer loop. X@7:FzU9
SELECT @Counter = 0 'G`xD3 E3,
WHILE ((@Counter < @OriginalSize / 16) AND (@Counter < 50000)) 2\F'So
BEGIN -- update &0{&4,
INSERT DummyTrans VALUES ('Fill Log') "Q{7X[$$^
DELETE DummyTrans ]puDqu5!
SELECT @Counter = @Counter + 1 `*i:z'
END aaI5x
EXEC (@TruncLog) YDgG2hT/2
END r/QI-Cf&
SELECT 'Final Size of ' + db_name() + ' LOG is ' + e|^.N[W
CONVERT(VARCHAR(30),size) + ' 8K pages or ' + Jt)J1CAYo
CONVERT(VARCHAR(30),(size*8/1024)) + 'MB' m`4N1egCt
FROM sysfiles R0F&!y!B
WHERE name = @LogicalFileName tw]
l
DROP TABLE DummyTrans G+m[W
SET NOCOUNT OFF D<[kbt5^7
8、说明:更改某个表 *]DO3Zw'
exec sp_changeobjectowner 'tablename','dbo' s1X?]A
9、存储更改全部表 j
~I_by
CREATE PROCEDURE dbo.User_ChangeObjectOwnerBatch I~-sBMm(w
@OldOwner as NVARCHAR(128), &C#?&AQ
@NewOwner as NVARCHAR(128) B.);Ju
AS hl8oE5MU
DECLARE @Name as NVARCHAR(128) *#GX~3A
DECLARE @Owner as NVARCHAR(128) .EjjCE/v-
DECLARE @OwnerName as NVARCHAR(128) dX-j3lM:#
DECLARE curObject CURSOR FOR H<qz
rO
select 'Name' = name, WGUd@lC~
'Owner' = user_name(uid) >=3oe.$)
from sysobjects p1IN%*IV+o
where user_name(uid)=@OldOwner &-Q_%eM^
order by name UAC"jy1D
OPEN curObject _gpf9ad
FETCH NEXT FROM curObject INTO @Name, @Owner G}nj
71=H
WHILE(@@FETCH_STATUS=0) oF s)UR
BEGIN gj
}Vnv1[
if @Owner=@OldOwner (
;KTV*1
begin #5X+.!L
set @OwnerName = @OldOwner + '.' + rtrim(@Name)
2l~qzT-
exec sp_changeobjectowner @OwnerName, @NewOwner #zc$cr
end Z0M|Bv9_
-- select @name,@NewOwner,@OldOwner t;y@;?~
FETCH NEXT FROM curObject INTO @Name, @Owner cHnd
gUW]
END 1WI^RlWd(
close curObject ]zI*}(adu
deallocate curObject k?Njge6@
GO ];u nR<H
10、SQL SERVER中直接循环写入数据 `/(9#E
declare @i int 6s$h _$[X
set @i=1 "}0)~,{xB
while @i<30 1.nYT*
begin ;Ji3|=4u
insert into test (userid) values(@i) _V3}F1?W
set @i=@i+1 ^+Vf*YY
8
end GvL\%0Ibx
小记存储过程中经常用到的本周,本月,本年函数 /@", 5U#
Dateadd(wk,datediff(wk,0,getdate()),-1) PE6ZzxR|U<
Dateadd(wk,datediff(wk,0,getdate()),6) TR:4$92:H
Dateadd(mm,datediff(mm,0,getdate()),0) o\nFSGkn
Dateadd(ms,-3,dateadd(mm,datediff(m,0,getdate())+1,0)) v\5`n@}4
Dateadd(yy,datediff(yy,0,getdate()),0) (?P\;yDG
Dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate())+1, 0)) 1Q$/L+uJ5
上面的SQL代码只是一个时间段 WT1d'@LY
Dateadd(wk,datediff(wk,0,getdate()),-1) yz%o?%@
Dateadd(wk,datediff(wk,0,getdate()),6) fhro"5/4
就是表示本周时间段. 'Ojxzz*tT
下面的SQL的条件部分,就是查询时间段在本周范围内的: +rKV*XX@
Where Time BETWEEN Dateadd(wk,datediff(wk,0,getdate()),-1) AND Dateadd(wk,datediff(wk,0,getdate()),6) Pe@*')o*
而在存储过程中 pc;`Fz/`7
select @begintime = Dateadd(wk,datediff(wk,0,getdate()),-1) &p55Cg@e)
select @endtime = Dateadd(wk,datediff(wk,0,getdate()),6) gbFHH,@