SQL语句先前写的时候,很容易把一些特殊的用法忘记,我特此整理了一下SQL语句操作。 iR0y"Cii
J.
@9zA&
IO> yIU[
一、基础 GH
xp7H
1、说明:创建数据库 DeYV$W
B
CREATE DATABASE database-name yppo6HGD
2、说明:删除数据库 D3A/l
drop database dbname S@sO;-^+
3、说明:备份sql server u-C)v*#L
--- 创建 备份数据的 device i@CxI<1'
USE master
WN<zkM~3
EXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1.dat' QdC<Sk!G
--- 开始 备份 W'.m'3#z
BACKUP DATABASE pubs TO testBack w*MpX
U<
4、说明:创建新表 Ca3~/KrM
create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..) X8`Sf>
根据已有的表创建新表: ]:\dPw`A
A:create table tab_new like tab_old (使用旧表创建新表) }d }lR
B:create table tab_new as select col1,col2... from tab_old definition only KY N0
5、说明:删除新表 E~:x(5'%d
drop table tabname jA/w|\d!
6、说明:增加一个列 D,ln)["xm
Alter table tabname add column col type C8 \^#5
注:列增加后将不能删除。DB2中列加上后数据类型也不能改变,唯一能改变的是增加varchar类型的长度。 TOAAQ
7、说明:添加主键: Alter table tabname add primary key(col) K4);HJ|=
说明:删除主键: Alter table tabname drop primary key(col) ,?XCyHSgWW
8、说明:创建索引:create [unique] index idxname on tabname(col....) bYPK h
删除索引:drop index idxname 'Z |mQZN
注:索引是不可更改的,想更改必须删除重新建。 ctJE+1#PH
9、说明:创建视图:create view viewname as select statement <^uBoKB/f
删除视图:drop view viewname bs'n+:X`
10、说明:几个简单的基本的sql语句 ]0\MmAJRn
选择:select * from table1 where 范围 VD\=`r)nT
插入:insert into table1(field1,field2) values(value1,value2) e0 T\tc
删除:delete from table1 where 范围 A +)`ZTuO
更新:update table1 set field1=value1 where 范围 2Wb]4-
查找:select * from table1 where field1 like '%value1%' ---like的语法很精妙,查资料! F}qc0
排序:select * from table1 order by field1,field2 [desc] Hq 188<
总数:select count as totalcount from table1 K_-MYs.
求和:select sum(field1) as sumvalue from table1 j8`BdKg
平均:select avg(field1) as avgvalue from table1 )F2OT<]m,
最大:select max(field1) as maxvalue from table1 $tS}LN_!
最小:select min(field1) as minvalue from table1 4a]P7fx-
/H==Hm/
*WT`o>
>dG[G>
11、说明:几个高级查询运算词 N.{D$"
6MkP |vr6
w+{LAS
A: UNION 运算符 \'bzt"f$j
UNION 运算符通过组合其他两个结果表(例如 TABLE1 和 TABLE2)并消去表中任何重复行而派生出一个结果表。当 ALL 随 UNION 一起使用时(即 UNION ALL),不消除重复行。两种情况下,派生表的每一行不是来自 TABLE1 就是来自 TABLE2。 O0y_Lm\
B: EXCEPT 运算符 09Cez\0
EXCEPT 运算符通过包括所有在 TABLE1 中但不在 TABLE2 中的行并消除所有重复行而派生出一个结果表。当 ALL 随 EXCEPT 一起使用时 (EXCEPT ALL),不消除重复行。 0K2`-mL
C: INTERSECT 运算符 C2Tyoza
INTERSECT 运算符通过只包括 TABLE1 和 TABLE2 中都有的行并消除所有重复行而派生出一个结果表。当 ALL 随 INTERSECT 一起使用时 (INTERSECT ALL),不消除重复行。 xZv#Es%#
注:使用运算词的几个查询结果行必须是一致的。 ?3xzd P
12、说明:使用外连接 jalg5`PU0
A、left outer join: @|%2f@h
左外连接(左连接):结果集几包括连接表的匹配行,也包括左连接表的所有行。 t`mV\)fa
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 Wiu"k%Qsh
B:right outer join: &JI8]JmU)
右外连接(右连接):结果集既包括连接表的匹配连接行,也包括右连接表的所有行。 (J!+(H8
C:full outer join: uRr o?m<
全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录。 4_cqT/
0_t`%l=
LE>]8[f6S
二、提升 *`RkTcG
1、说明:复制表(只复制结构,源表名:a 新表名:b) (Access可用) `^y7f
法一:select * into b from a where 1<>1 ][h}
法二:select top 0 * into b from a
(ICd}
2、说明:拷贝表(拷贝数据,源表名:a 目标表名:b) (Access可用) j,dR,N d
insert into b(a, b, c) select d,e,f from b; bbyg8;/
3、说明:跨数据库之间表的拷贝(具体数据使用绝对路径) (Access可用) hfy_3} _
insert into b(a, b, c) select d,e,f from b in '具体数据库' where 条件 "6?0h[uff
例子:..from b in '"&Server.MapPath(".")&"\data.mdb" &"' where.. /~f'}]W
4、说明:子查询(表名1:a 表名2:b) NTI+
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) }~e%J(
5、说明:显示文章、提交人和最后回复时间 H+Sz=tg5
select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b )%@J=&G8TT
6、说明:外连接查询(表名1:a 表名2:b) /RC7"QzL
select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c qeZ? 7#Gf
7、说明:在线视图查询(表名1:a ) 46&/gehr
select * from (SELECT a,b,c FROM a) T where t.a > 1; NPe%F+X
8、说明:between的用法,between限制查询数据范围时包括了边界值,not between不包括 <HVt
V9R
select * from table1 where time between time1 and time2 EJNU761
select a,b,c, from table1 where a not between 数值1 and 数值2 >s?S+W[L
9、说明:in 的使用方法 :zF,A,)
select * from table1 where a [not] in ('值1','值2','值4','值6') 'y3!fN=h
10、说明:两张关联表,删除主表中已经在副表中没有的信息 ITT@,
delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 ) OH(waKq2I
11、说明:四表联查问题: ;VO:ph4Aj
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 ..... <<R*2b
12、说明:日程安排提前五分钟提醒 b`O'1r\Y;
SQL: select * from 日程安排 where datediff('minute',f开始时间,getdate())>5 DZPPJ2 }
13、说明:一条sql 语句搞定数据库分页 ;x@~A^<el
select top 10 b.* from (select top 20 主键字段,排序字段 from 表名 order by 排序字段 desc) a,表名 b where b.主键字段 = a.主键字段 order by a.排序字段 <?4V
14、说明:前10条记录 }d}Ke_Q0
select top 10 * form table1 where 范围 exUu7&*:
15、说明:选择在每一组b值相同的数据中对应的a最大的记录的所有信息(类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等.) $@"g^,n
select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b) ^RtIh-Z.9
16、说明:包括所有在 TableA 中但不在 TableB和TableC 中的行并消除所有重复行而派生出一个结果表 RuVGG)
(select a from tableA ) except (select a from tableB) except (select a from tableC) <3C*Z"aQ>|
17、说明:随机取出10条数据 -I,$_
select top 10 * from tablename order by newid() ?'{SX9
18、说明:随机选择记录 g~A`N=r;h
select newid() HqT#$}rv
19、说明:删除重复记录 "mvt>X
Delete from tablename where id not in (select max(id) from tablename group by col1,col2,...) h|{]B,.Lh
20、说明:列出数据库里所有的表名 DG:Z=LuJr
select name from sysobjects where type='U' [}0haTYc4
21、说明:列出表里的所有的 Q| ?L*Pq2I
select name from syscolumns where id=object_id('TableName') 76h ,]xi
22、说明:列示type、vender、pcs字段,以type字段排列,case可以方便地实现多重选择,类似select 中的case。 =mp;.k95
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 zsyIV!(
显示结果: #KexvP&*
type vender pcs (\YltC@q%
电脑 A 1 6.nCV0xA
电脑 A 1 s{\8om'-
光盘 B 2 <+vw@M
光盘 A 2 +Kbjzh3<wG
手机 B 3 O*)Vhw'pK
手机 C 3 F%D.zvKN
23、说明:初始化表table1 XXn67sF/
TRUNCATE TABLE table1 ]a*d#
24、说明:选择从10到15的记录 0*D$R`$
select top 5 * from (select top 15 * from table order by id asc) table_别名 order by id desc %.-4!vj
GM f
`A,>
nwRc%C``UK
V7fq4O^:
三、技巧 ::{Q1F
1、1=1,1=2的使用,在SQL语句组合时用的较多 /zVOK4BqN+
"where 1=1" 是表示选择全部 "where 1=2"全部不选, %%gc2s
如: !/i{l
if @strWhere !='' !0L Wa"
begin MH9q ;?.J
set @strSQL = 'select count(*) as Total from [' + @tblName + '] where ' + @strWhere ;LSANr&
end 1 +{{EOZ4
else %oa-WmWm
begin *Y7u'v
set @strSQL = 'select count(*) as Total from [' + @tblName + ']' W_(j3pV?Ml
end EGU
0)<
我们可以直接写成 X296tA>C`
set @strSQL = 'select count(*) as Total from [' + @tblName + '] where 1=1 安定 '+ @strWhere 9BBmw(M}
2、收缩数据库 kr:^tbJ
--重建索引 a:IC)]j$_
DBCC REINDEX EF}\brD1
DBCC INDEXDEFRAG nIy}#MUd|q
--收缩数据和日志 Y}|X|!0x
DBCC SHRINKDB vJc- 6EO
DBCC SHRINKFILE 'RYIW/a
3、压缩数据库 `1{ZqRFQ
dbcc shrinkdatabase(dbname) MSqVlj
4、转移数据库给新用户以已存在用户权限 q" sed]
exec sp_change_users_login 'update_one','newname','oldname' -g Sa_8R
go >kDQkhZ
5、检查备份集 dkBIx$t
RESTORE VERIFYONLY from disk='E:\dvbbs.bak' 1.{z3_S21:
6、修复数据库 {|_M
#w~&
ALTER DATABASE [dvbbs] SET SINGLE_USER *>'V1b4}
GO Yz"#^j}Kg
DBCC CHECKDB('dvbbs',repair_allow_data_loss) WITH TABLOCK })8N5C+KU
GO vB|hZTW
ALTER DATABASE [dvbbs] SET MULTI_USER a PfO$b:
GO J1RJ*mo7,
7、日志清除 GmEJhr.3`=
SET NOCOUNT ON cyv`B3}
DECLARE @LogicalFileName sysname, 4n g]\ituS
@MaxMinutes INT, JZ*/,|1}EC
@NewSize INT BmMGx8P
USE tablename -- 要操作的数据库名 6x[}g
SELECT @LogicalFileName = 'tablename_log', -- 日志文件名 A _
N;
@MaxMinutes = 10, -- Limit on time allowed to wrap log. ZC`wO%,
@NewSize = 1 -- 你想设定的日志文件的大小(M) %wvdn
-- Setup / initialize yyRiP|hJ
DECLARE @OriginalSize int '(yAfL 9}
SELECT @OriginalSize = size g:D>.lKd
FROM sysfiles -)]Yr #Q
WHERE name = @LogicalFileName e~[/i\
SELECT 'Original Size of ' + db_name() + ' LOG is ' + L Mbn
CONVERT(VARCHAR(30),@OriginalSize) + ' 8K pages or ' + [{<`o5qR
CONVERT(VARCHAR(30),(@OriginalSize*8/1024)) + 'MB' [-k
FROM sysfiles m^f0V2M_
WHERE name = @LogicalFileName (%e.:W${
CREATE TABLE DummyTrans 2%@4]
(DummyColumn char (8000) not null) ukfQe }I
DECLARE @Counter INT, ag#S6E^%S
@StartTime DATETIME, 8Pn#+IvCE
@TruncLog VARCHAR(255) %x{kc3PnO
SELECT @StartTime = GETDATE(), m=A(NKZ
@TruncLog = 'BACKUP LOG ' + db_name() + ' WITH TRUNCATE_ONLY' >G*eNn
DBCC SHRINKFILE (@LogicalFileName, @NewSize) foF({4q7b^
EXEC (@TruncLog) ](9Xvy
-- Wrap the log if necessary. q?oP?cCw
WHILE @MaxMinutes > DATEDIFF (mi, @StartTime, GETDATE()) -- time has not expired wQH<gJE/:
AND @OriginalSize = (SELECT size FROM sysfiles WHERE name = @LogicalFileName) (*nT(Adk
AND (@OriginalSize * 8 /1024) > @NewSize [.'|_l
BEGIN -- Outer loop. y'~U%,ki6
SELECT @Counter = 0 +]A:M6P:{v
WHILE ((@Counter < @OriginalSize / 16) AND (@Counter < 50000))
bv9i*]
BEGIN -- update gG:Vt}N
INSERT DummyTrans VALUES ('Fill Log') EQyC1j
DELETE DummyTrans LX7FaW
SELECT @Counter = @Counter + 1 '4Ixqb+
END 4Lh!8g=/
EXEC (@TruncLog) [.8BTj1%
END %C'?@,7C
SELECT 'Final Size of ' + db_name() + ' LOG is ' + K{cD+=]{
CONVERT(VARCHAR(30),size) + ' 8K pages or ' + DV+xg3\(>1
CONVERT(VARCHAR(30),(size*8/1024)) + 'MB' t?ZI".>
FROM sysfiles +xSHL|:b
WHERE name = @LogicalFileName ^aMg/.j
DROP TABLE DummyTrans 5uNJx5g
SET NOCOUNT OFF 4 \K7xM!
8、说明:更改某个表 S)k*?dQ##R
exec sp_changeobjectowner 'tablename','dbo' *1
]uH e
9、存储更改全部表 EXwo,?I
CREATE PROCEDURE dbo.User_ChangeObjectOwnerBatch oMD>Ywc-
@OldOwner as NVARCHAR(128), D},>mfzF
@NewOwner as NVARCHAR(128) 5k3n\sqZA
AS HU}7zK2
DECLARE @Name as NVARCHAR(128) 1N^[.=
DECLARE @Owner as NVARCHAR(128) -p&" y3<p
DECLARE @OwnerName as NVARCHAR(128) .hP D$o
DECLARE curObject CURSOR FOR \H~T>j{N
select 'Name' = name, NP#w+Qw
'Owner' = user_name(uid) a
%'the
from sysobjects ia~HQ$'+n
where user_name(uid)=@OldOwner Xy&A~F
order by name 5\sd3<:+
OPEN curObject el<s8:lA
FETCH NEXT FROM curObject INTO @Name, @Owner ooL!TSGD
WHILE(@@FETCH_STATUS=0) 9ni1f{k
BEGIN .E1rqB G
if @Owner=@OldOwner E7 Ul;d
begin gQelD6c
set @OwnerName = @OldOwner + '.' + rtrim(@Name) i2A81>68<
exec sp_changeobjectowner @OwnerName, @NewOwner eRstD>r
end S8w _ii3zd
-- select @name,@NewOwner,@OldOwner +I:Unp
FETCH NEXT FROM curObject INTO @Name, @Owner cAqLE\h
END {G0T$,'DR
close curObject z'U1bMg
deallocate curObject "f2$w
GO 9:[ 9v
10、SQL SERVER中直接循环写入数据 Lpz>>}
declare @i int ,GIyq)
set @i=1 `?qF$g9u~
while @i<30 n;Q7X>-f8`
begin A5RN5`}
insert into test (userid) values(@i) k&q;JyUi
set @i=@i+1 \*y-g@-{W$
end V-2(?auZd
小记存储过程中经常用到的本周,本月,本年函数 |t&>5HM
Dateadd(wk,datediff(wk,0,getdate()),-1) \0I_<
Dateadd(wk,datediff(wk,0,getdate()),6) sPQQ"|wU
Dateadd(mm,datediff(mm,0,getdate()),0) [{,T.;'<j
Dateadd(ms,-3,dateadd(mm,datediff(m,0,getdate())+1,0)) Apag{Z]^B
Dateadd(yy,datediff(yy,0,getdate()),0) LTCb@L{^i
Dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate())+1, 0)) YnS#H"
上面的SQL代码只是一个时间段 wn, KY$/
Dateadd(wk,datediff(wk,0,getdate()),-1) DE8n+Rm
Dateadd(wk,datediff(wk,0,getdate()),6) #PW9:_BE
就是表示本周时间段. #ut
下面的SQL的条件部分,就是查询时间段在本周范围内的: ]e^&aR5f"
Where Time BETWEEN Dateadd(wk,datediff(wk,0,getdate()),-1) AND Dateadd(wk,datediff(wk,0,getdate()),6) Jk11fn;\>
而在存储过程中 J T7nG.9
select @begintime = Dateadd(wk,datediff(wk,0,getdate()),-1) G1tY) _-8[
select @endtime = Dateadd(wk,datediff(wk,0,getdate()),6) rjAn@!|:+