SQL语句先前写的时候,很容易把一些特殊的用法忘记,我特此整理了一下SQL语句操作。 )+t5G>yKK
pjj
5
iL 4SL}P
一、基础 'v|2}T*
1、说明:创建数据库 $fKwJFr
CREATE DATABASE database-name P'9aZd
2、说明:删除数据库 om_&|9B)
drop database dbname h.=B!wKK
3、说明:备份sql server J|FyY)_
--- 创建 备份数据的 device &<Gq-IN
USE master 1]>KuXd
r
EXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1.dat' IPxfjBC+J
--- 开始 备份 oZCi_g 5i
BACKUP DATABASE pubs TO testBack g41Lh3dj
4、说明:创建新表 g[M@
create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..) bOz\-=au
根据已有的表创建新表: ')1sw%[2
A:create table tab_new like tab_old (使用旧表创建新表) }BogE$tc
B:create table tab_new as select col1,col2... from tab_old definition only H9)uni
5、说明:删除新表 ''v1Pv-
drop table tabname Xi{(1o4%
6、说明:增加一个列 8&C(0H]1
Alter table tabname add column col type Jj6kZK
注:列增加后将不能删除。DB2中列加上后数据类型也不能改变,唯一能改变的是增加varchar类型的长度。 M.8!BB7\8e
7、说明:添加主键: Alter table tabname add primary key(col) w|nVK9.
说明:删除主键: Alter table tabname drop primary key(col) :s'%IGy>:
8、说明:创建索引:create [unique] index idxname on tabname(col....) 93WYZNpX
删除索引:drop index idxname ~v54$#CB
注:索引是不可更改的,想更改必须删除重新建。 &HXSO,@
9、说明:创建视图:create view viewname as select statement FY|x<-f
删除视图:drop view viewname hE6tu'
10、说明:几个简单的基本的sql语句 =-VV`
选择:select * from table1 where 范围 >Ed^dsb&
插入:insert into table1(field1,field2) values(value1,value2) mW-@-5Wda
删除:delete from table1 where 范围 I(<G;ft<}
更新:update table1 set field1=value1 where 范围 u3. PHZ
查找:select * from table1 where field1 like '%value1%' ---like的语法很精妙,查资料! >rFvT>@NU
排序:select * from table1 order by field1,field2 [desc] %9D@W*Z
总数:select count as totalcount from table1 /3TorB~Y
求和:select sum(field1) as sumvalue from table1 I@S<D"af
平均:select avg(field1) as avgvalue from table1 KncoIw
最大:select max(field1) as maxvalue from table1 'j)eqoj
最小:select min(field1) as minvalue from table1 '9/kDkt!
^n2w6U0
R$@.{d&:w
|Gf{}
11、说明:几个高级查询运算词 o7T|w~F~R
1I+5
:> q?s
A: UNION 运算符 g^C6"rsnl
UNION 运算符通过组合其他两个结果表(例如 TABLE1 和 TABLE2)并消去表中任何重复行而派生出一个结果表。当 ALL 随 UNION 一起使用时(即 UNION ALL),不消除重复行。两种情况下,派生表的每一行不是来自 TABLE1 就是来自 TABLE2。
(KQt%]
B: EXCEPT 运算符 =5|5j!i=q
EXCEPT 运算符通过包括所有在 TABLE1 中但不在 TABLE2 中的行并消除所有重复行而派生出一个结果表。当 ALL 随 EXCEPT 一起使用时 (EXCEPT ALL),不消除重复行。 j>b OnCp~
C: INTERSECT 运算符 r#Fu<so,
INTERSECT 运算符通过只包括 TABLE1 和 TABLE2 中都有的行并消除所有重复行而派生出一个结果表。当 ALL 随 INTERSECT 一起使用时 (INTERSECT ALL),不消除重复行。 qJ/C*Wqic
注:使用运算词的几个查询结果行必须是一致的。 5,c`
12、说明:使用外连接 u9gr@06
A、left outer join: *"CvB{XF&Z
左外连接(左连接):结果集几包括连接表的匹配行,也包括左连接表的所有行。 lhI;K4#
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 |K_B{v.
B:right outer join: ~/x42|t
右外连接(右连接):结果集既包括连接表的匹配连接行,也包括右连接表的所有行。 P&tK}Se^V
C:full outer join: "QF083$
全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录。 ;dFe >`~
+i>q;=~
*@&
"MZ/M
二、提升 P8VU&b\
1、说明:复制表(只复制结构,源表名:a 新表名:b) (Access可用) `l+SJLyJ%
法一:select * into b from a where 1<>1 J9 =gv0
法二:select top 0 * into b from a |d3agfS[n
2、说明:拷贝表(拷贝数据,源表名:a 目标表名:b) (Access可用) *Z:PB%d5
insert into b(a, b, c) select d,e,f from b; (>K$gAQH
3、说明:跨数据库之间表的拷贝(具体数据使用绝对路径) (Access可用) 2$o[
insert into b(a, b, c) select d,e,f from b in '具体数据库' where 条件 0/ Ht;(
例子:..from b in '"&Server.MapPath(".")&"\data.mdb" &"' where.. b
tu:@s8ci
4、说明:子查询(表名1:a 表名2:b) (Lo2fY5
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) hjG1fgEj
5、说明:显示文章、提交人和最后回复时间 }gW}Vr <
select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b 7asq]Y}<
6、说明:外连接查询(表名1:a 表名2:b) 'MUrszOO.e
select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c qc6IH9i`
7、说明:在线视图查询(表名1:a ) dc>y7$2
select * from (SELECT a,b,c FROM a) T where t.a > 1; ~tLR
8、说明:between的用法,between限制查询数据范围时包括了边界值,not between不包括 _'7/99]4g}
select * from table1 where time between time1 and time2 Ax0,7,8y
select a,b,c, from table1 where a not between 数值1 and 数值2 +Y~+o-_
9、说明:in 的使用方法 W =zG
select * from table1 where a [not] in ('值1','值2','值4','值6') ??m7xH5u1
10、说明:两张关联表,删除主表中已经在副表中没有的信息 4PWr;&
delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 ) -"zu"H~t4
11、说明:四表联查问题: x]ti3?w
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 ..... <n\.S
12、说明:日程安排提前五分钟提醒 _6m3$k_[MJ
SQL: select * from 日程安排 where datediff('minute',f开始时间,getdate())>5 @EY}iK~
13、说明:一条sql 语句搞定数据库分页 K*Jtyy}r
select top 10 b.* from (select top 20 主键字段,排序字段 from 表名 order by 排序字段 desc) a,表名 b where b.主键字段 = a.主键字段 order by a.排序字段 (OqJet2{+
14、说明:前10条记录 X4$e2f
select top 10 * form table1 where 范围 [j?<9
15、说明:选择在每一组b值相同的数据中对应的a最大的记录的所有信息(类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等.) gHx-m2N
select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b) HUC2RM?FN
16、说明:包括所有在 TableA 中但不在 TableB和TableC 中的行并消除所有重复行而派生出一个结果表 +I<Sq_-
(select a from tableA ) except (select a from tableB) except (select a from tableC) $P(nh'\
17、说明:随机取出10条数据 gxOmbQt@;
select top 10 * from tablename order by newid() W\,lII0
18、说明:随机选择记录
?Qig$
select newid() )!d1<p3
19、说明:删除重复记录 .e"Qv*[^
Delete from tablename where id not in (select max(id) from tablename group by col1,col2,...) r(i)9RI+(
20、说明:列出数据库里所有的表名 4c=kT@=jX
select name from sysobjects where type='U' f4S@lyYF
21、说明:列出表里的所有的 {{3H\
rR
select name from syscolumns where id=object_id('TableName') GX)QIe~;qJ
22、说明:列示type、vender、pcs字段,以type字段排列,case可以方便地实现多重选择,类似select 中的case。 g8+,wSE
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 zb/Xfu.)?6
显示结果: @WHd(ka!
type vender pcs @S7=6RKa[
电脑 A 1 H040-Q;S'
电脑 A 1 =BS'oBn^6
光盘 B 2 XQOprIJ
U
光盘 A 2 F?} *ovy
手机 B 3 udGGDH
手机 C 3 zt2-w/[Q
23、说明:初始化表table1 }qv-lO
TRUNCATE TABLE table1 XyphQ}\u
24、说明:选择从10到15的记录 E ZKz-}
select top 5 * from (select top 15 * from table order by id asc) table_别名 order by id desc ? SP7vQ/
9Nu#&_2R
|V\.[F2Fe
4p8jV*:@{
三、技巧 f*vk1dS:*3
1、1=1,1=2的使用,在SQL语句组合时用的较多 mzB#O;3=
"where 1=1" 是表示选择全部 "where 1=2"全部不选, pqN[G=0
如: k6L373e#Q
if @strWhere !='' )[sO5X7'^
begin 8MeXVhM
set @strSQL = 'select count(*) as Total from [' + @tblName + '] where ' + @strWhere gVU\^KN]
end pMp9O/u%
else 1K9?a;.
begin [|n-x3h
set @strSQL = 'select count(*) as Total from [' + @tblName + ']' (eG]Cp@
end R6Mxdm2P}
我们可以直接写成 W 'a~pB1I
set @strSQL = 'select count(*) as Total from [' + @tblName + '] where 1=1 安定 '+ @strWhere Zfv(\SI
2、收缩数据库 0Eu$-)
--重建索引 f_h"gZWV
DBCC REINDEX Z034wn\N
DBCC INDEXDEFRAG ]8>UII,US
--收缩数据和日志 'uACoME@
DBCC SHRINKDB hav?mnVJ
DBCC SHRINKFILE N#['fg'
3、压缩数据库 +N$7=oGC
dbcc shrinkdatabase(dbname) /v)!m&6]>
4、转移数据库给新用户以已存在用户权限 Qz)8eIO:
exec sp_change_users_login 'update_one','newname','oldname' 0D3+R1>_D
go k*3_)
S
-
5、检查备份集 o>;0NF| }
RESTORE VERIFYONLY from disk='E:\dvbbs.bak' sQAc"S
6、修复数据库 &IEBZB\/+&
ALTER DATABASE [dvbbs] SET SINGLE_USER T{4fa^c2J
GO 1+tt'
DBCC CHECKDB('dvbbs',repair_allow_data_loss) WITH TABLOCK NE2sD
GO @b*T4hwA.
ALTER DATABASE [dvbbs] SET MULTI_USER uAS8F=9xP
GO X,EYa>RSy_
7、日志清除 a/<pf\O
SET NOCOUNT ON P9i9<pR
DECLARE @LogicalFileName sysname, vDeG20.?Z
@MaxMinutes INT, sQ:VrXwP
@NewSize INT y7)[cvB
USE tablename -- 要操作的数据库名 N"1x]1'
SELECT @LogicalFileName = 'tablename_log', -- 日志文件名 RrU~"P1C
@MaxMinutes = 10, -- Limit on time allowed to wrap log. k\&IFSp
@NewSize = 1 -- 你想设定的日志文件的大小(M) <<On*#80w
-- Setup / initialize W/r?0E
DECLARE @OriginalSize int |z|)r"*\4
SELECT @OriginalSize = size \v3>Eo[
FROM sysfiles |@L &yg,x
WHERE name = @LogicalFileName *_/eAi/WG
SELECT 'Original Size of ' + db_name() + ' LOG is ' + @EP{VV
CONVERT(VARCHAR(30),@OriginalSize) + ' 8K pages or ' + 7cmr
*y
CONVERT(VARCHAR(30),(@OriginalSize*8/1024)) + 'MB' ]7S7CVDk4
FROM sysfiles sJI-
WHERE name = @LogicalFileName ym*#ZE`B!
CREATE TABLE DummyTrans Y0X94k.u
(DummyColumn char (8000) not null) BdB`
DECLARE @Counter INT, Q`p}X&^a
@StartTime DATETIME, dbT^9: Q
@TruncLog VARCHAR(255) }:9|*m<$t
SELECT @StartTime = GETDATE(), ?sf2h:\N
@TruncLog = 'BACKUP LOG ' + db_name() + ' WITH TRUNCATE_ONLY' `-K)K<
DBCC SHRINKFILE (@LogicalFileName, @NewSize) /zG-\eU
EXEC (@TruncLog) v(@+6#&
-- Wrap the log if necessary. F `pyhc>1;
WHILE @MaxMinutes > DATEDIFF (mi, @StartTime, GETDATE()) -- time has not expired -=Eq/su%
AND @OriginalSize = (SELECT size FROM sysfiles WHERE name = @LogicalFileName) 95?5=TF
AND (@OriginalSize * 8 /1024) > @NewSize [+MH[1Vr={
BEGIN -- Outer loop. C*y6~AYN#
SELECT @Counter = 0 *fvI.cKiGP
WHILE ((@Counter < @OriginalSize / 16) AND (@Counter < 50000)) 3w^J"O/T
BEGIN -- update ^,Y~M_=
INSERT DummyTrans VALUES ('Fill Log') W`/jz/
DELETE DummyTrans r6`^>c
SELECT @Counter = @Counter + 1 J'&B:PZObB
END !/Bw,y ri<
EXEC (@TruncLog) Avv
END mam5G!$
SELECT 'Final Size of ' + db_name() + ' LOG is ' + *Nf4bH%MN
CONVERT(VARCHAR(30),size) + ' 8K pages or ' + 4&]To@>
CONVERT(VARCHAR(30),(size*8/1024)) + 'MB' )>/j&>%
FROM sysfiles ^tg6JB;s
WHERE name = @LogicalFileName d%_78nOh"
DROP TABLE DummyTrans Qk~0a?#y5
SET NOCOUNT OFF $-fjrQ
8、说明:更改某个表 ~Miin
exec sp_changeobjectowner 'tablename','dbo' {F(-s"1;xO
9、存储更改全部表 Q9eYF-+
CREATE PROCEDURE dbo.User_ChangeObjectOwnerBatch m['v3m:
@OldOwner as NVARCHAR(128), jWv3O&+?X
@NewOwner as NVARCHAR(128) =2g[tsY
AS =JbdsYI(
DECLARE @Name as NVARCHAR(128) Ic{'H2~4,
DECLARE @Owner as NVARCHAR(128) B=q)}aWc
DECLARE @OwnerName as NVARCHAR(128) 71L\t3fG
DECLARE curObject CURSOR FOR ."F'5eTT~
select 'Name' = name, >d27[%
'Owner' = user_name(uid) _!C)r*0(
from sysobjects z%}CBTm
where user_name(uid)=@OldOwner B'KXQa-$O
order by name 9o_ g_q
OPEN curObject qrM{b=
FETCH NEXT FROM curObject INTO @Name, @Owner QSn;a 4f
WHILE(@@FETCH_STATUS=0) [TbG55
BEGIN zqvRkMWcM
if @Owner=@OldOwner
M\y~0uZ
begin HoIKx_
set @OwnerName = @OldOwner + '.' + rtrim(@Name) J:~[j
exec sp_changeobjectowner @OwnerName, @NewOwner p-Rm,xyL%
end l?@MUsg+
-- select @name,@NewOwner,@OldOwner "
g0-u(Y
FETCH NEXT FROM curObject INTO @Name, @Owner qUEd
E`B
END iJdrY6qd
close curObject EG(`E9DZ
deallocate curObject ^:cb
$9F
GO wv7p,9Z[
10、SQL SERVER中直接循环写入数据 hyk|+z`B
declare @i int H)j[eZP
set @i=1 V`R)#G>IH%
while @i<30 e}](6"t`5
begin i3M?D}(Bs
insert into test (userid) values(@i) Pghva*&
set @i=@i+1 AT%*
~tr
end 9*-pden
l
小记存储过程中经常用到的本周,本月,本年函数 M\\e e3Ih
Dateadd(wk,datediff(wk,0,getdate()),-1) +
4V1>e+
Dateadd(wk,datediff(wk,0,getdate()),6) =qV4Sje|q
Dateadd(mm,datediff(mm,0,getdate()),0) Wk\mgGn+
Dateadd(ms,-3,dateadd(mm,datediff(m,0,getdate())+1,0)) 7,W]zKH
Dateadd(yy,datediff(yy,0,getdate()),0) {FV,j.D
Dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate())+1, 0)) vB{;N
上面的SQL代码只是一个时间段 .-('C> @
Dateadd(wk,datediff(wk,0,getdate()),-1) fW5"4,
Dateadd(wk,datediff(wk,0,getdate()),6) !7mvyc!'!
就是表示本周时间段. ~{1/*&P
下面的SQL的条件部分,就是查询时间段在本周范围内的: NK
Where Time BETWEEN Dateadd(wk,datediff(wk,0,getdate()),-1) AND Dateadd(wk,datediff(wk,0,getdate()),6) Rm,[D)D^0N
而在存储过程中 koncWyW
select @begintime = Dateadd(wk,datediff(wk,0,getdate()),-1) v2M"b?Q
select @endtime = Dateadd(wk,datediff(wk,0,getdate()),6) u_}`y1Xu#