SQL语句先前写的时候,很容易把一些特殊的用法忘记,我特此整理了一下SQL语句操作。 9*j$U$:'
{K >}eO:K
/nVGr]t_pj
一、基础
@1O.;
1、说明:创建数据库 u%I |o s]
CREATE DATABASE database-name TAKvE=a;
2、说明:删除数据库 -)$5[jM]
drop database dbname !5=S2<UX
3、说明:备份sql server Zp
<^|=D
--- 创建 备份数据的 device m}o4Vr;"
USE master b]xE^zM-I`
EXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1.dat' zpBkP-%}E
--- 开始 备份 [}Pi $at
BACKUP DATABASE pubs TO testBack p1B~F
4、说明:创建新表 ><3!J+<?
create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..) }q D0-
根据已有的表创建新表:
ZBl!7_[_
A:create table tab_new like tab_old (使用旧表创建新表) {<y.G1<.
B:create table tab_new as select col1,col2... from tab_old definition only yZw5?{g@
5、说明:删除新表 |%c"Avc
drop table tabname N
Obw/9JO
6、说明:增加一个列 \O(~:KN
Alter table tabname add column col type B"=w9w]
注:列增加后将不能删除。DB2中列加上后数据类型也不能改变,唯一能改变的是增加varchar类型的长度。 Gsa~zGN
7、说明:添加主键: Alter table tabname add primary key(col) +/4wioGm
说明:删除主键: Alter table tabname drop primary key(col) Y]])Tq;h5
8、说明:创建索引:create [unique] index idxname on tabname(col....) Xjs`iK=w
删除索引:drop index idxname U3b&/z|b?
注:索引是不可更改的,想更改必须删除重新建。 $hq'9}ASOL
9、说明:创建视图:create view viewname as select statement ~3,k8C"pRq
删除视图:drop view viewname n,8bQP=&
10、说明:几个简单的基本的sql语句 Gx/kel[Y}
选择:select * from table1 where 范围 m)Sdogt_
插入:insert into table1(field1,field2) values(value1,value2) WI}cXXUKm0
删除:delete from table1 where 范围 $s"{C"4q
更新:update table1 set field1=value1 where 范围 VL2+"<
查找:select * from table1 where field1 like '%value1%' ---like的语法很精妙,查资料! s{dgUX
排序:select * from table1 order by field1,field2 [desc] qEajT"?
总数:select count as totalcount from table1 =]m,7 v Rq
求和:select sum(field1) as sumvalue from table1 bK#SxV
平均:select avg(field1) as avgvalue from table1 xnvG5
最大:select max(field1) as maxvalue from table1 ;<N%D=;}@
最小:select min(field1) as minvalue from table1 Td,s"p>Vq
@e:=
D
cT(=pMt8>
P]%)c6Uh
11、说明:几个高级查询运算词 ~>B`T%=H
Nn='9s9F?}
WO!'("
A: UNION 运算符 ,jq:%Y[KZ
UNION 运算符通过组合其他两个结果表(例如 TABLE1 和 TABLE2)并消去表中任何重复行而派生出一个结果表。当 ALL 随 UNION 一起使用时(即 UNION ALL),不消除重复行。两种情况下,派生表的每一行不是来自 TABLE1 就是来自 TABLE2。 nN5fP<H2x
B: EXCEPT 运算符 Q.} guI\
EXCEPT 运算符通过包括所有在 TABLE1 中但不在 TABLE2 中的行并消除所有重复行而派生出一个结果表。当 ALL 随 EXCEPT 一起使用时 (EXCEPT ALL),不消除重复行。 i)th] 1K%
C: INTERSECT 运算符 L6Io u
INTERSECT 运算符通过只包括 TABLE1 和 TABLE2 中都有的行并消除所有重复行而派生出一个结果表。当 ALL 随 INTERSECT 一起使用时 (INTERSECT ALL),不消除重复行。 UAe8Ct=YJ
注:使用运算词的几个查询结果行必须是一致的。 Ge1b_?L_
12、说明:使用外连接 ToX--w4
A、left outer join: 7(l>Ck3B#
左外连接(左连接):结果集几包括连接表的匹配行,也包括左连接表的所有行。 Nk;ywC"e;
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 PnZC
I!Mw
B:right outer join: 2Og<e|
右外连接(右连接):结果集既包括连接表的匹配连接行,也包括右连接表的所有行。 0)rayzv
C:full outer join: ,{X}C
全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录。 )f,9 h
| Pi! UZB
-CLBf'a
二、提升 aUk]wiwIR9
1、说明:复制表(只复制结构,源表名:a 新表名:b) (Access可用) WS//0
法一:select * into b from a where 1<>1 N;gY5;0m
法二:select top 0 * into b from a X m3r)Bm'3
2、说明:拷贝表(拷贝数据,源表名:a 目标表名:b) (Access可用) c8LMvL
insert into b(a, b, c) select d,e,f from b; bs0[ a 1/
3、说明:跨数据库之间表的拷贝(具体数据使用绝对路径) (Access可用) _p^$.\k"
insert into b(a, b, c) select d,e,f from b in '具体数据库' where 条件 H3LuRGe&2
例子:..from b in '"&Server.MapPath(".")&"\data.mdb" &"' where.. !<>*|a
4、说明:子查询(表名1:a 表名2:b)
JKV&c=I
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) b/?)_pg
5、说明:显示文章、提交人和最后回复时间 8]D0)
select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b M+*K-zt0
6、说明:外连接查询(表名1:a 表名2:b) ![9$ru
select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c V1haAP[#
7、说明:在线视图查询(表名1:a ) ^.9DfA0
select * from (SELECT a,b,c FROM a) T where t.a > 1; =Cd{bj.8
8、说明:between的用法,between限制查询数据范围时包括了边界值,not between不包括 _L+j6N.h1
select * from table1 where time between time1 and time2 (hEg&@
select a,b,c, from table1 where a not between 数值1 and 数值2 \/64Xv3L0
9、说明:in 的使用方法 1,P\dGmu
select * from table1 where a [not] in ('值1','值2','值4','值6') 09qfnQG
10、说明:两张关联表,删除主表中已经在副表中没有的信息 d$"?8r4:K
delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 ) ""A6n{4
11、说明:四表联查问题: /DjsnU~3
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 ..... 7>=
12、说明:日程安排提前五分钟提醒 3N5@<:2`
SQL: select * from 日程安排 where datediff('minute',f开始时间,getdate())>5 w{ ;Sp?Os
13、说明:一条sql 语句搞定数据库分页 <4n"LJ9
select top 10 b.* from (select top 20 主键字段,排序字段 from 表名 order by 排序字段 desc) a,表名 b where b.主键字段 = a.主键字段 order by a.排序字段 l(W?]{C[%
14、说明:前10条记录 e_"m\e#N
select top 10 * form table1 where 范围 3"juj'
15、说明:选择在每一组b值相同的数据中对应的a最大的记录的所有信息(类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等.) 4/%Y@Z5
select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b) `NTtw;%Y
16、说明:包括所有在 TableA 中但不在 TableB和TableC 中的行并消除所有重复行而派生出一个结果表 N<ux4tz
(select a from tableA ) except (select a from tableB) except (select a from tableC) H32o7]lT
17、说明:随机取出10条数据 ]&N>F8.L+
select top 10 * from tablename order by newid() XOLE=zdSp
18、说明:随机选择记录 Np i)R)
select newid() F]t=5
-O<
19、说明:删除重复记录 >bd@2au9!
Delete from tablename where id not in (select max(id) from tablename group by col1,col2,...) \KzH5 ?
20、说明:列出数据库里所有的表名 cg o
select name from sysobjects where type='U' ?J,,RK.
21、说明:列出表里的所有的 J.'%=q(Sb
select name from syscolumns where id=object_id('TableName') d14 n>
22、说明:列示type、vender、pcs字段,以type字段排列,case可以方便地实现多重选择,类似select 中的case。 ^Ua6.RH8
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 e`:^7$
显示结果: \Z,{De%
type vender pcs `a!9_%|8
电脑 A 1 PXqG;o*Q*?
电脑 A 1 +g kJrw
光盘 B 2 eWNg?*/
光盘 A 2 CmV &+C$V%
手机 B 3 !\$V?*p7
手机 C 3 W+/_0GgQ3
23、说明:初始化表table1 _m[DieR
TRUNCATE TABLE table1 >:4`y"0
24、说明:选择从10到15的记录 jCXBp>9$M
select top 5 * from (select top 15 * from table order by id asc) table_别名 order by id desc &q@brX<,=
.6T0d
4,1
Q4hY\\Hi
R :(-"GW'
三、技巧 L~^5Ez6U
1、1=1,1=2的使用,在SQL语句组合时用的较多 E3l*_b0
"where 1=1" 是表示选择全部 "where 1=2"全部不选, r~2hTie
如: awwSgy
if @strWhere !='' d$n31F
begin s5rD+g]E`
set @strSQL = 'select count(*) as Total from [' + @tblName + '] where ' + @strWhere @"MQ6u G>
end [8^q3o7n
else CGzu(@dd\
begin 9^ZtbmUf
set @strSQL = 'select count(*) as Total from [' + @tblName + ']' SJ<v< B
end atF#0*e>
我们可以直接写成 yW(|auq
set @strSQL = 'select count(*) as Total from [' + @tblName + '] where 1=1 安定 '+ @strWhere S<-nlBs.
2、收缩数据库 0#Lmajs
--重建索引 Eh ";irE
DBCC REINDEX $xbW*w
DBCC INDEXDEFRAG k}Q<#
--收缩数据和日志 =#,`k<v%I
DBCC SHRINKDB yk)]aqic
DBCC SHRINKFILE 6o7t eX
3、压缩数据库 e).;;0
dbcc shrinkdatabase(dbname) [!yA#{xl,
4、转移数据库给新用户以已存在用户权限 ]/H6%"CTa
exec sp_change_users_login 'update_one','newname','oldname' /KX+'@
go ($kw*H{Ah^
5、检查备份集 \0d'y#Gp*
RESTORE VERIFYONLY from disk='E:\dvbbs.bak' ,aLwOmO
6、修复数据库 W.?/p~
ALTER DATABASE [dvbbs] SET SINGLE_USER E "}@SaB-
GO ,!b<SQ5M
DBCC CHECKDB('dvbbs',repair_allow_data_loss) WITH TABLOCK |5tZ*$nGa
GO (or"5}\6-
ALTER DATABASE [dvbbs] SET MULTI_USER 4&;iORw&E4
GO BhzD V
7、日志清除 <y] 67:"<v
SET NOCOUNT ON QcW8A ,\q
DECLARE @LogicalFileName sysname, 3_Xu3hNH!
@MaxMinutes INT, >>,G3/Zd*
@NewSize INT F{!pii5O9
USE tablename -- 要操作的数据库名 w\YS5!P,V
SELECT @LogicalFileName = 'tablename_log', -- 日志文件名 ,d,2Q
@MaxMinutes = 10, -- Limit on time allowed to wrap log. Xs2 jR14`
@NewSize = 1 -- 你想设定的日志文件的大小(M) w|-3X
-- Setup / initialize ]5c(:T F
DECLARE @OriginalSize int "mf$E|
SELECT @OriginalSize = size jt on \9
FROM sysfiles ESIP+
WHERE name = @LogicalFileName U`i5B;k}-
SELECT 'Original Size of ' + db_name() + ' LOG is ' + +q'1P}e
CONVERT(VARCHAR(30),@OriginalSize) + ' 8K pages or ' + 26rg-?;V^
CONVERT(VARCHAR(30),(@OriginalSize*8/1024)) + 'MB' kuy?n-1g
FROM sysfiles j*G: 8Lg
WHERE name = @LogicalFileName robg1
CREATE TABLE DummyTrans 0^gY4qx[u
(DummyColumn char (8000) not null) 1wKXOy=v0
DECLARE @Counter INT, ^]nLE]M
@StartTime DATETIME, 7>__ fQu
@TruncLog VARCHAR(255) HDhISPg
SELECT @StartTime = GETDATE(), 9+^)?JUYll
@TruncLog = 'BACKUP LOG ' + db_name() + ' WITH TRUNCATE_ONLY' +h4W<YnW
DBCC SHRINKFILE (@LogicalFileName, @NewSize) c\1X NPGG
EXEC (@TruncLog) @%R4V[Lo.
-- Wrap the log if necessary. n jWe^
WHILE @MaxMinutes > DATEDIFF (mi, @StartTime, GETDATE()) -- time has not expired o+A1-&qhN
AND @OriginalSize = (SELECT size FROM sysfiles WHERE name = @LogicalFileName) W&*&O,c
AND (@OriginalSize * 8 /1024) > @NewSize z{
:;Rb
BEGIN -- Outer loop. 'R79,)|;[
SELECT @Counter = 0 :xPo*#[Z(A
WHILE ((@Counter < @OriginalSize / 16) AND (@Counter < 50000)) "mW'tm1+
BEGIN -- update oNAnJ+_
INSERT DummyTrans VALUES ('Fill Log') igfQ,LWe!
DELETE DummyTrans |(z{)yWbC[
SELECT @Counter = @Counter + 1 b4e~Z
END %- 540V{q
EXEC (@TruncLog) &sWr)>vs
END p8~lGuH
SELECT 'Final Size of ' + db_name() + ' LOG is ' + !%,7*F(
CONVERT(VARCHAR(30),size) + ' 8K pages or ' + jU j\<aW
CONVERT(VARCHAR(30),(size*8/1024)) + 'MB' P3&s<mh
FROM sysfiles ORs:S$Nt$
WHERE name = @LogicalFileName A_zCSRF,
DROP TABLE DummyTrans BB/wL_=:
SET NOCOUNT OFF i D IY|
8、说明:更改某个表 I?3b}#&V9
exec sp_changeobjectowner 'tablename','dbo' KFd
+7C9
9、存储更改全部表 'F/oR/4,
CREATE PROCEDURE dbo.User_ChangeObjectOwnerBatch h#hr'3bI1
@OldOwner as NVARCHAR(128), B>^6tdz
@NewOwner as NVARCHAR(128) n[iwi
AS ^?`fN'!p
DECLARE @Name as NVARCHAR(128) {fR\yWkt?
DECLARE @Owner as NVARCHAR(128) cERIj0~
DECLARE @OwnerName as NVARCHAR(128) -[7+g
DECLARE curObject CURSOR FOR p|-MwCeH
select 'Name' = name, SN}K=)KF#
'Owner' = user_name(uid) mrP48#Y+l
from sysobjects S{+t>en
where user_name(uid)=@OldOwner x|0C0a\"A
order by name l/'GbuECm
OPEN curObject f=F:Af!
FETCH NEXT FROM curObject INTO @Name, @Owner A*y4<'}<
WHILE(@@FETCH_STATUS=0) 89FAh6u E
BEGIN Xxg|01
if @Owner=@OldOwner V/ G1C^'/
begin .KA-=$~J1
set @OwnerName = @OldOwner + '.' + rtrim(@Name) [`\VgKeu
exec sp_changeobjectowner @OwnerName, @NewOwner >zW2w2O3
end j~-N2b6z
-- select @name,@NewOwner,@OldOwner xSmG,}3mF
FETCH NEXT FROM curObject INTO @Name, @Owner pux IJ
END rFg$7
close curObject o72r `2
deallocate curObject "`49m7q1H
GO 'v6@5t19j
10、SQL SERVER中直接循环写入数据 UA6id|G
declare @i int o8g7wM]M
set @i=1 lvke!~#
while @i<30 q`c!!Lg
begin kXwAw]ogN
insert into test (userid) values(@i) c4tw)O-X
set @i=@i+1 9Y:I)^ek
end 5^g*
小记存储过程中经常用到的本周,本月,本年函数 0Qt!w(
Dateadd(wk,datediff(wk,0,getdate()),-1) E )_n?>Ar
Dateadd(wk,datediff(wk,0,getdate()),6) 6nW)2LV
Dateadd(mm,datediff(mm,0,getdate()),0) PlkZ)S7C
Dateadd(ms,-3,dateadd(mm,datediff(m,0,getdate())+1,0)) 6<];}M_{
Dateadd(yy,datediff(yy,0,getdate()),0) wXQxZuk[
Dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate())+1, 0)) YhN<vZ}U!~
上面的SQL代码只是一个时间段 ]/=R ABi
Dateadd(wk,datediff(wk,0,getdate()),-1) S0^a)#D &
Dateadd(wk,datediff(wk,0,getdate()),6) 7S a9
就是表示本周时间段. R.^]{ 5
下面的SQL的条件部分,就是查询时间段在本周范围内的: f*o
Where Time BETWEEN Dateadd(wk,datediff(wk,0,getdate()),-1) AND Dateadd(wk,datediff(wk,0,getdate()),6) Njc@5*rJ&
而在存储过程中 kW/G=_6
select @begintime = Dateadd(wk,datediff(wk,0,getdate()),-1) RpivO,
select @endtime = Dateadd(wk,datediff(wk,0,getdate()),6) lx:$EJ