SQL语句先前写的时候,很容易把一些特殊的用法忘记,我特此整理了一下SQL语句操作。 ub%q<sE*
vPi+8)
EUgs2Fsb3
一、基础 VTdZ&%@
1、说明:创建数据库 60Z)AQs;+J
CREATE DATABASE database-name CpXv?uU
2、说明:删除数据库 mB\|<2
drop database dbname rX[R`,`>Z[
3、说明:备份sql server Ho/5e*X
--- 创建 备份数据的 device ,MJZ*"V/3
USE master KpL82
EXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1.dat' X}Lp!.i9o
--- 开始 备份 sAxn
;
`
BACKUP DATABASE pubs TO testBack LO229`ARr|
4、说明:创建新表 FoLwS%+yO
create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..)
;L7<mU
根据已有的表创建新表: =}[V69a
A:create table tab_new like tab_old (使用旧表创建新表) A`KTm(
B:create table tab_new as select col1,col2... from tab_old definition only >=bO@)[
5、说明:删除新表 li[g =A,
drop table tabname aw`mB,5U
6、说明:增加一个列 2iu;7/
Alter table tabname add column col type O-k(5Zb
注:列增加后将不能删除。DB2中列加上后数据类型也不能改变,唯一能改变的是增加varchar类型的长度。 Q1rwTg\
7、说明:添加主键: Alter table tabname add primary key(col) ]pt @
说明:删除主键: Alter table tabname drop primary key(col) S@_GjCpn
8、说明:创建索引:create [unique] index idxname on tabname(col....) -3Ffk:
删除索引:drop index idxname 7iJlW&W
注:索引是不可更改的,想更改必须删除重新建。 @S}'_g
9、说明:创建视图:create view viewname as select statement |@+
x9|'W
删除视图:drop view viewname <8Ad\MU
10、说明:几个简单的基本的sql语句 Nuj%8om6
选择:select * from table1 where 范围 R[z6 c)
插入:insert into table1(field1,field2) values(value1,value2) LX8vVj8K
删除:delete from table1 where 范围 ~(c<ioIf
更新:update table1 set field1=value1 where 范围 "o1/gV
查找:select * from table1 where field1 like '%value1%' ---like的语法很精妙,查资料!
`@p*1
排序:select * from table1 order by field1,field2 [desc] [|3
%~s|Sv
总数:select count as totalcount from table1 O/-xkzR*
求和:select sum(field1) as sumvalue from table1 Y#G '[N>
平均:select avg(field1) as avgvalue from table1 Vj_
$%0
最大:select max(field1) as maxvalue from table1 ,70|I{,Km
最小:select min(field1) as minvalue from table1 .R1)i-^
#Rs7Ieu+
OG.`\G|
6^p6v
11、说明:几个高级查询运算词 +um;
eL7
r8qee$^M
607#d):Y
A: UNION 运算符 6^~&sA
UNION 运算符通过组合其他两个结果表(例如 TABLE1 和 TABLE2)并消去表中任何重复行而派生出一个结果表。当 ALL 随 UNION 一起使用时(即 UNION ALL),不消除重复行。两种情况下,派生表的每一行不是来自 TABLE1 就是来自 TABLE2。 0-@waK
B: EXCEPT 运算符 Z^sO`C
EXCEPT 运算符通过包括所有在 TABLE1 中但不在 TABLE2 中的行并消除所有重复行而派生出一个结果表。当 ALL 随 EXCEPT 一起使用时 (EXCEPT ALL),不消除重复行。 wL*z+>5
C: INTERSECT 运算符 .{6TX"M
INTERSECT 运算符通过只包括 TABLE1 和 TABLE2 中都有的行并消除所有重复行而派生出一个结果表。当 ALL 随 INTERSECT 一起使用时 (INTERSECT ALL),不消除重复行。 iU &V}p
注:使用运算词的几个查询结果行必须是一致的。 :%Bo)0a9
12、说明:使用外连接 X(8]9
A、left outer join: N%0Z>
G
左外连接(左连接):结果集几包括连接表的匹配行,也包括左连接表的所有行。 L%"&_v#a^
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 q+N}AKawB
B:right outer join: &B)
F_E I
右外连接(右连接):结果集既包括连接表的匹配连接行,也包括右连接表的所有行。 Jyd%!v
C:full outer join: Z/64E^
全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录。 (T@ov~@
|(w x6H:
k&Sg`'LG8
二、提升 P)T:6K
1、说明:复制表(只复制结构,源表名:a 新表名:b) (Access可用) Dv$xP)./
法一:select * into b from a where 1<>1 bBZvL
法二:select top 0 * into b from a j"f]pzg&
2、说明:拷贝表(拷贝数据,源表名:a 目标表名:b) (Access可用) )%Y$FLB
insert into b(a, b, c) select d,e,f from b; ALFw[1X
3、说明:跨数据库之间表的拷贝(具体数据使用绝对路径) (Access可用) <#c2Hg%jh
insert into b(a, b, c) select d,e,f from b in '具体数据库' where 条件 0^;{b^!(
例子:..from b in '"&Server.MapPath(".")&"\data.mdb" &"' where.. S>6APQ-
4、说明:子查询(表名1:a 表名2:b) ohwQ%NDl
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) w ^r*qi"
5、说明:显示文章、提交人和最后回复时间 nkpQM$FW
select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b $XJe)
6、说明:外连接查询(表名1:a 表名2:b) |/q *Fg[f
select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c ,7eN m>$
7、说明:在线视图查询(表名1:a ) j@9A!5<CCk
select * from (SELECT a,b,c FROM a) T where t.a > 1; }!2|*Y
8、说明:between的用法,between限制查询数据范围时包括了边界值,not between不包括 :r|dXW
select * from table1 where time between time1 and time2 JAgec` T%
select a,b,c, from table1 where a not between 数值1 and 数值2 p.zU9rID
9、说明:in 的使用方法 &fW;;>
select * from table1 where a [not] in ('值1','值2','值4','值6') 2-8<uU y
10、说明:两张关联表,删除主表中已经在副表中没有的信息 KxY|:-"Tt
delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 ) J?%Z7&/M>
11、说明:四表联查问题: w=OT^d 9n
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 ..... b+{,c@1rd
12、说明:日程安排提前五分钟提醒 xe
6x!
SQL: select * from 日程安排 where datediff('minute',f开始时间,getdate())>5 _I2AJn`#
13、说明:一条sql 语句搞定数据库分页 4pF%G
select top 10 b.* from (select top 20 主键字段,排序字段 from 表名 order by 排序字段 desc) a,表名 b where b.主键字段 = a.主键字段 order by a.排序字段 }=wSfr9g
14、说明:前10条记录 :^l`m9
select top 10 * form table1 where 范围 1y
6H 2
15、说明:选择在每一组b值相同的数据中对应的a最大的记录的所有信息(类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等.) ?Hq`*I?b9
select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b) 3B>!9:w~f
16、说明:包括所有在 TableA 中但不在 TableB和TableC 中的行并消除所有重复行而派生出一个结果表 ,5<-\"{]
(select a from tableA ) except (select a from tableB) except (select a from tableC) [3j]r{0I
17、说明:随机取出10条数据 iE$0-Qe[3
select top 10 * from tablename order by newid() ~jJu*s$?
18、说明:随机选择记录 gp;(M~we
select newid() nPKf~|\1{
19、说明:删除重复记录 <;=X7l+
Delete from tablename where id not in (select max(id) from tablename group by col1,col2,...) X\M0Q%8
20、说明:列出数据库里所有的表名 #B54p@.}
select name from sysobjects where type='U' F> ..eK
21、说明:列出表里的所有的 puDy&T
select name from syscolumns where id=object_id('TableName') rGx1>xd(k
22、说明:列示type、vender、pcs字段,以type字段排列,case可以方便地实现多重选择,类似select 中的case。 $+$+;1[
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 sjztT<{Q^-
显示结果: t@b';Cuv
type vender pcs No j6Ina
电脑 A 1 a}MOhM6T
电脑 A 1 >/Slk{
光盘 B 2 7quhp\
光盘 A 2 .0Cpqn,[
手机 B 3 <TDgv%eg0
手机 C 3 pp/Cn4"w
23、说明:初始化表table1 D_'Zucq
TRUNCATE TABLE table1 B>gC75
24、说明:选择从10到15的记录 VYvHpsI
select top 5 * from (select top 15 * from table order by id asc) table_别名 order by id desc *S*;rLH9c
%]d^B|
8DyE
)0!hw|0|
三、技巧 _bFX(~37z?
1、1=1,1=2的使用,在SQL语句组合时用的较多 i |cSO2O+
"where 1=1" 是表示选择全部 "where 1=2"全部不选, XYf;72*
如: 9].!mpR
if @strWhere !='' I 8e{%PK
begin <^OGJ}G
set @strSQL = 'select count(*) as Total from [' + @tblName + '] where ' + @strWhere n&k1'KL&
end |7%M:7Q
else mR?OSeeB
begin R$wo{{KX
set @strSQL = 'select count(*) as Total from [' + @tblName + ']' 3]/w3|y
end t hTY('m
我们可以直接写成 izOtt^#DZt
set @strSQL = 'select count(*) as Total from [' + @tblName + '] where 1=1 安定 '+ @strWhere t4
$cMf
2、收缩数据库 gy,B+~p
--重建索引 qJUu9[3'm
DBCC REINDEX lfb]xu]O
DBCC INDEXDEFRAG 'lg6<M%#[
--收缩数据和日志 ?;!l-Dy
DBCC SHRINKDB -k")#1
DBCC SHRINKFILE & Z*&&
3、压缩数据库 , En
D3
|
dbcc shrinkdatabase(dbname) KTd4pW?w
4、转移数据库给新用户以已存在用户权限 /zM
exec sp_change_users_login 'update_one','newname','oldname' Vtr0=-m&
go LBbk]I
5、检查备份集 r>A,7{
RESTORE VERIFYONLY from disk='E:\dvbbs.bak' KGFmC[
6、修复数据库 pv;}Sv$
]-
ALTER DATABASE [dvbbs] SET SINGLE_USER l. !5/\
GO k oZqoP
DBCC CHECKDB('dvbbs',repair_allow_data_loss) WITH TABLOCK Dtt[a
GO (?;Fnq
ALTER DATABASE [dvbbs] SET MULTI_USER `+{|k)2B
GO ,accw}G
7、日志清除 tBp dKJn##
SET NOCOUNT ON |'Z6M];8t
DECLARE @LogicalFileName sysname, n:x6bPal]
@MaxMinutes INT, -"#;U`.oh7
@NewSize INT _.yBX\tf[
USE tablename -- 要操作的数据库名 u 6$fF=
SELECT @LogicalFileName = 'tablename_log', -- 日志文件名 >@`D@_v
@MaxMinutes = 10, -- Limit on time allowed to wrap log. _T)dmhG
@NewSize = 1 -- 你想设定的日志文件的大小(M) \k;*Ej~.
-- Setup / initialize V1,O7m+F2
DECLARE @OriginalSize int [C.Pzo
SELECT @OriginalSize = size 7J.alV4`/
FROM sysfiles vSX71
WHERE name = @LogicalFileName Sc`W'q^X
SELECT 'Original Size of ' + db_name() + ' LOG is ' + Si.3Je[q
CONVERT(VARCHAR(30),@OriginalSize) + ' 8K pages or ' + Tz:mj
CONVERT(VARCHAR(30),(@OriginalSize*8/1024)) + 'MB' rq:R6e
FROM sysfiles ]|@RWzA
WHERE name = @LogicalFileName Xq` '^)
CREATE TABLE DummyTrans mtvfG
(DummyColumn char (8000) not null) uR"(0_
DECLARE @Counter INT, "O!J6
@StartTime DATETIME, H3nx8R$j](
@TruncLog VARCHAR(255) VMe~aUd
SELECT @StartTime = GETDATE(), ;n?H/(6X8>
@TruncLog = 'BACKUP LOG ' + db_name() + ' WITH TRUNCATE_ONLY' |Rf4^vN
DBCC SHRINKFILE (@LogicalFileName, @NewSize) &J,MJ{w6"
EXEC (@TruncLog) 2<y!3OeN
-- Wrap the log if necessary. 7?Q<kB=f
WHILE @MaxMinutes > DATEDIFF (mi, @StartTime, GETDATE()) -- time has not expired L*"Q5NzB]
AND @OriginalSize = (SELECT size FROM sysfiles WHERE name = @LogicalFileName) 8fY1~\G:\
AND (@OriginalSize * 8 /1024) > @NewSize [f!sBJ!
BEGIN -- Outer loop. \,+act"v
SELECT @Counter = 0 Dh*Uv,
WHILE ((@Counter < @OriginalSize / 16) AND (@Counter < 50000)) C{H:-"\J9
BEGIN -- update ^/h,C^/;
INSERT DummyTrans VALUES ('Fill Log') aq@/sMn
DELETE DummyTrans `
zeZ7:
SELECT @Counter = @Counter + 1 'P3CgpF<Z2
END I&,gCZ#
EXEC (@TruncLog) 0sD"Hu
END [y F>W$Bn%
SELECT 'Final Size of ' + db_name() + ' LOG is ' + \'q 9,tP
CONVERT(VARCHAR(30),size) + ' 8K pages or ' + `%SFu
CONVERT(VARCHAR(30),(size*8/1024)) + 'MB' 82O#Fe q
FROM sysfiles 0B7cpw>_J
WHERE name = @LogicalFileName 07:CcT
DROP TABLE DummyTrans oj/,vO:QT
SET NOCOUNT OFF )S]4
Kt_
8、说明:更改某个表 z^;*&J
exec sp_changeobjectowner 'tablename','dbo' Y&6vTU
9、存储更改全部表 D~P I_*h.
CREATE PROCEDURE dbo.User_ChangeObjectOwnerBatch !yI , ~`Z
@OldOwner as NVARCHAR(128), ]>M{Qn*
@NewOwner as NVARCHAR(128) +]
s"* 'V$
AS ^rO3B?_
DECLARE @Name as NVARCHAR(128) 0pYO-@E
DECLARE @Owner as NVARCHAR(128) 'Y Bz?l9
DECLARE @OwnerName as NVARCHAR(128) |gxT-ZM
DECLARE curObject CURSOR FOR T:p,!?kc7
select 'Name' = name, .KSPr
'Owner' = user_name(uid) Z/n\Ak sE
from sysobjects uQIa"u7
where user_name(uid)=@OldOwner '85@U`e.
order by name ky0Fm
W
OPEN curObject J5b>mTvb
FETCH NEXT FROM curObject INTO @Name, @Owner Yx>y(Whu.
WHILE(@@FETCH_STATUS=0) @Fv"j9j-3G
BEGIN {x$jGiag+8
if @Owner=@OldOwner jODx&dVr
begin tXDO@YH3S
set @OwnerName = @OldOwner + '.' + rtrim(@Name) }D02*s
exec sp_changeobjectowner @OwnerName, @NewOwner zkHwoAD;t8
end "ph&hd}S
-- select @name,@NewOwner,@OldOwner wDJbax?
FETCH NEXT FROM curObject INTO @Name, @Owner TY6
D.ikA
END ?0QoYA@.$
close curObject wcDHx#~
deallocate curObject Y??8P
GO BIovPvq;i
10、SQL SERVER中直接循环写入数据 <!g q9
declare @i int WP{!|d&
set @i=1 Xk8+
while @i<30 _?$P?
begin
Q}.zE+
insert into test (userid) values(@i) a7KP_[_(
set @i=@i+1 qw={gZ
end P4@<`Eb
小记存储过程中经常用到的本周,本月,本年函数 hYOUuC
Dateadd(wk,datediff(wk,0,getdate()),-1) tu{y
Dateadd(wk,datediff(wk,0,getdate()),6) b~uz\%'3
Dateadd(mm,datediff(mm,0,getdate()),0) $Pv;>fHu
Dateadd(ms,-3,dateadd(mm,datediff(m,0,getdate())+1,0)) t
1gH9
Dateadd(yy,datediff(yy,0,getdate()),0) ozv:$>v@"
Dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate())+1, 0)) 7v\K,P8
上面的SQL代码只是一个时间段 B]jN~CO?
Dateadd(wk,datediff(wk,0,getdate()),-1) WB~
^R<g
Dateadd(wk,datediff(wk,0,getdate()),6) ,QU2xw D[
就是表示本周时间段. "_dh6naZX
下面的SQL的条件部分,就是查询时间段在本周范围内的: <4V]>[{W
Where Time BETWEEN Dateadd(wk,datediff(wk,0,getdate()),-1) AND Dateadd(wk,datediff(wk,0,getdate()),6) =gL~E9\
而在存储过程中 fS2 ^$"B|
select @begintime = Dateadd(wk,datediff(wk,0,getdate()),-1) k=L(C^VP
select @endtime = Dateadd(wk,datediff(wk,0,getdate()),6) :y#KR\T1