SQL语句先前写的时候,很容易把一些特殊的用法忘记,我特此整理了一下SQL语句操作。 >7[.
{Y
n,q+EZd
Y?a*-"
一、基础 wC+_S*M-K
1、说明:创建数据库 $6kVhE!;
CREATE DATABASE database-name $vlq]6V8
2、说明:删除数据库 PGF=q|j9K
drop database dbname *7u~`
3、说明:备份sql server _~ZNX+4
--- 创建 备份数据的 device /7/d
u[P6
USE master OXd617
EXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1.dat' B2w\
--- 开始 备份 -!f)P=S
BACKUP DATABASE pubs TO testBack "l &=a1l
4、说明:创建新表 8QDs4Bv|
create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..) U` uP^
根据已有的表创建新表: r BQFC4L
A:create table tab_new like tab_old (使用旧表创建新表) 7=(rk
B:create table tab_new as select col1,col2... from tab_old definition only rJ|Q%utYz
5、说明:删除新表 DN3#W w2[r
drop table tabname BQu_)@
6、说明:增加一个列 kclClB:PS
Alter table tabname add column col type W ZdEfY{
注:列增加后将不能删除。DB2中列加上后数据类型也不能改变,唯一能改变的是增加varchar类型的长度。 #; CC"
7、说明:添加主键: Alter table tabname add primary key(col) >>oR@
说明:删除主键: Alter table tabname drop primary key(col) #9M6 q
8、说明:创建索引:create [unique] index idxname on tabname(col....) ^x-vOGlR
删除索引:drop index idxname uu@Y]0-
注:索引是不可更改的,想更改必须删除重新建。 B8;jRY
9、说明:创建视图:create view viewname as select statement PY-
1 oP
删除视图:drop view viewname =
_X#JP79
10、说明:几个简单的基本的sql语句 Q\|72NWS
选择:select * from table1 where 范围 2#:/C:
插入:insert into table1(field1,field2) values(value1,value2) S{'/=Px+
删除:delete from table1 where 范围 ErIAS6HS'
更新:update table1 set field1=value1 where 范围 U]jHe
查找:select * from table1 where field1 like '%value1%' ---like的语法很精妙,查资料! (N{Rda*8
排序:select * from table1 order by field1,field2 [desc] 3omFd#EP
总数:select count as totalcount from table1 7N9~nEU
求和:select sum(field1) as sumvalue from table1 +RWP;rk
平均:select avg(field1) as avgvalue from table1 HI)MBrj;r
最大:select max(field1) as maxvalue from table1 4+2XPaIm
最小:select min(field1) as minvalue from table1 - e0C
Bp
u>SGa @R)
exT
O#*o
y=7WnQc
11、说明:几个高级查询运算词 D1]%2:
B7BXS*_b
R1OC7q
A: UNION 运算符 `]%\Y>(a}
UNION 运算符通过组合其他两个结果表(例如 TABLE1 和 TABLE2)并消去表中任何重复行而派生出一个结果表。当 ALL 随 UNION 一起使用时(即 UNION ALL),不消除重复行。两种情况下,派生表的每一行不是来自 TABLE1 就是来自 TABLE2。 O_^O1
B: EXCEPT 运算符 b~dm+5W7
EXCEPT 运算符通过包括所有在 TABLE1 中但不在 TABLE2 中的行并消除所有重复行而派生出一个结果表。当 ALL 随 EXCEPT 一起使用时 (EXCEPT ALL),不消除重复行。 6$c,#%Jt*
C: INTERSECT 运算符 )NAC9:8!
INTERSECT 运算符通过只包括 TABLE1 和 TABLE2 中都有的行并消除所有重复行而派生出一个结果表。当 ALL 随 INTERSECT 一起使用时 (INTERSECT ALL),不消除重复行。 =2!AK[KxX
注:使用运算词的几个查询结果行必须是一致的。 U
?'$E\
12、说明:使用外连接 =.NZ{G
A、left outer join: 9ZFvN*Zf'
左外连接(左连接):结果集几包括连接表的匹配行,也包括左连接表的所有行。 $.{CA-~%[
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 KzD5>Xf]4$
B:right outer join: o (fZZ`6Y
右外连接(右连接):结果集既包括连接表的匹配连接行,也包括右连接表的所有行。 g-lF{Z
C:full outer join: 5y-8_)y8o
全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录。 AKs=2N>7
C$Pe<C#
2ED^uc:
0S
二、提升 uis;S)+
1、说明:复制表(只复制结构,源表名:a 新表名:b) (Access可用) juOOD
法一:select * into b from a where 1<>1 0s )B~
法二:select top 0 * into b from a i\hH .7G1
2、说明:拷贝表(拷贝数据,源表名:a 目标表名:b) (Access可用) f[v~U<\R
insert into b(a, b, c) select d,e,f from b; ~3-2Iu^F
3、说明:跨数据库之间表的拷贝(具体数据使用绝对路径) (Access可用) 6!P];3&o\A
insert into b(a, b, c) select d,e,f from b in '具体数据库' where 条件 ^@f%A<
例子:..from b in '"&Server.MapPath(".")&"\data.mdb" &"' where.. 0w^\sf%s
4、说明:子查询(表名1:a 表名2:b) ZK,}3b{
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) ~um+r],@@
5、说明:显示文章、提交人和最后回复时间 ;m6Mm`[i<
select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b wUkLe-n,dE
6、说明:外连接查询(表名1:a 表名2:b) 3?|gBiX
select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c gEC*JbA.3
7、说明:在线视图查询(表名1:a ) F%QZe*m[
select * from (SELECT a,b,c FROM a) T where t.a > 1; p_h)|*W{
8、说明:between的用法,between限制查询数据范围时包括了边界值,not between不包括 dv3+x\`9
select * from table1 where time between time1 and time2 4
4%jz-m
select a,b,c, from table1 where a not between 数值1 and 数值2 k#"Pv"
9、说明:in 的使用方法 +LddW0h+=8
select * from table1 where a [not] in ('值1','值2','值4','值6') +<&\*VR
10、说明:两张关联表,删除主表中已经在副表中没有的信息 s)Sa KE*d
delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 ) +SCUS]
11、说明:四表联查问题: `L0aQ$'>z
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 ..... DDxNqVVt4
12、说明:日程安排提前五分钟提醒 Zur7"OkQ
SQL: select * from 日程安排 where datediff('minute',f开始时间,getdate())>5 OdX-.FFl
13、说明:一条sql 语句搞定数据库分页 CORX .PQ
select top 10 b.* from (select top 20 主键字段,排序字段 from 表名 order by 排序字段 desc) a,表名 b where b.主键字段 = a.主键字段 order by a.排序字段 5MY+O\
14、说明:前10条记录 V+M2Gf
select top 10 * form table1 where 范围 "o#N6Qu71
15、说明:选择在每一组b值相同的数据中对应的a最大的记录的所有信息(类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等.) -f?Rr:#
select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b) B@!a@0,,_
16、说明:包括所有在 TableA 中但不在 TableB和TableC 中的行并消除所有重复行而派生出一个结果表 )Y':u_Lo
(select a from tableA ) except (select a from tableB) except (select a from tableC) ]P/eg$u'I
17、说明:随机取出10条数据 x h[4d
select top 10 * from tablename order by newid() w`XwW#!}@$
18、说明:随机选择记录 `K[:<p}
select newid() tm\ <w H
19、说明:删除重复记录 wqDRFZ1*P
Delete from tablename where id not in (select max(id) from tablename group by col1,col2,...) g*8LdH6mq
20、说明:列出数据库里所有的表名 b:fy
select name from sysobjects where type='U' '>FJk`iI
21、说明:列出表里的所有的 -x
)(2|
select name from syscolumns where id=object_id('TableName') pGw|T~e%
22、说明:列示type、vender、pcs字段,以type字段排列,case可以方便地实现多重选择,类似select 中的case。 TnET1$@qr*
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 YLk; ^?
显示结果: Mi'Q5m
type vender pcs uYjJDLYoHl
电脑 A 1 kfb+OE:7
电脑 A 1 0^44${bA
光盘 B 2 3}O.B
r|
光盘 A 2 g3{)AX[Uy
手机 B 3 e
#l/jFJU
手机 C 3 rN?
L8
23、说明:初始化表table1 bu"Jb4_a>
TRUNCATE TABLE table1 N]cGJU>$
24、说明:选择从10到15的记录 Y+N^_2@+C
select top 5 * from (select top 15 * from table order by id asc) table_别名 order by id desc ^5vFF@to
p-V#nPb
D[{p~x^
z79L2lJn
三、技巧 JA7HO|
1、1=1,1=2的使用,在SQL语句组合时用的较多 6 .DJRY
"where 1=1" 是表示选择全部 "where 1=2"全部不选, g-xbb&]
如: ;@K,>$ur-
if @strWhere !='' G[u_Uu=>
begin /1++ 8=
set @strSQL = 'select count(*) as Total from [' + @tblName + '] where ' + @strWhere X?$Eb
end 0O4'Ts ?
else 9m56oT'U{
begin "hz(A.THi
set @strSQL = 'select count(*) as Total from [' + @tblName + ']' s<0yQ-=.?N
end Vja' :i
我们可以直接写成 FVLXq0<Cj
set @strSQL = 'select count(*) as Total from [' + @tblName + '] where 1=1 安定 '+ @strWhere L]0+u\(
2、收缩数据库 IDBhhv3ak
--重建索引 +AyQ4Q(-o
DBCC REINDEX xMg&>}5
DBCC INDEXDEFRAG MnFem $ @
--收缩数据和日志 b0LjNO@<
DBCC SHRINKDB OB3AZH$
DBCC SHRINKFILE ><OdHRh@#
3、压缩数据库 z2t;!]"'l
dbcc shrinkdatabase(dbname) _%l+v
4、转移数据库给新用户以已存在用户权限 W"Dj+/uS
exec sp_change_users_login 'update_one','newname','oldname' 9.e?<u*-z
go n]4)~ZIAU
5、检查备份集 heZ)+}U~
RESTORE VERIFYONLY from disk='E:\dvbbs.bak' S|;a=K&hS
6、修复数据库 If6wkY6sR
ALTER DATABASE [dvbbs] SET SINGLE_USER g2C-)*'{yh
GO `ZN@L<I6
DBCC CHECKDB('dvbbs',repair_allow_data_loss) WITH TABLOCK =Z/'|;Vd_x
GO +YT/od1t7
ALTER DATABASE [dvbbs] SET MULTI_USER 6N.mSnp
GO =pWpHbB.
7、日志清除 /0SG
SET NOCOUNT ON &{&lCBN
DECLARE @LogicalFileName sysname, H*|Bukgt/M
@MaxMinutes INT, 05*_h0}
@NewSize INT m'k`p5[=h
USE tablename -- 要操作的数据库名 wO}
3i6
SELECT @LogicalFileName = 'tablename_log', -- 日志文件名 c%pW'UE&
@MaxMinutes = 10, -- Limit on time allowed to wrap log. CCq<y
@NewSize = 1 -- 你想设定的日志文件的大小(M) K1O/>dN_\O
-- Setup / initialize 9YHSL[
DECLARE @OriginalSize int SfJ/(q
SELECT @OriginalSize = size k;zbq
FROM sysfiles 0x# 6L
WHERE name = @LogicalFileName b9|F>3?r>
SELECT 'Original Size of ' + db_name() + ' LOG is ' + ^1,]?F^
CONVERT(VARCHAR(30),@OriginalSize) + ' 8K pages or ' + \+GXUnkj
CONVERT(VARCHAR(30),(@OriginalSize*8/1024)) + 'MB' )2YU|
FROM sysfiles \Qk:\aLR
WHERE name = @LogicalFileName WbH/K]/1)h
CREATE TABLE DummyTrans 1sc #!^Oo
(DummyColumn char (8000) not null) +KFK..
DECLARE @Counter INT, 1I3u~J3]/
@StartTime DATETIME, l0D.7>aj
@TruncLog VARCHAR(255) a0)+=*$
SELECT @StartTime = GETDATE(), ec1g7w-n
@TruncLog = 'BACKUP LOG ' + db_name() + ' WITH TRUNCATE_ONLY'
4EB$e?
DBCC SHRINKFILE (@LogicalFileName, @NewSize) eV9:AN }K=
EXEC (@TruncLog) K1:F{*
-- Wrap the log if necessary. 2SG|]=
WHILE @MaxMinutes > DATEDIFF (mi, @StartTime, GETDATE()) -- time has not expired ^0{S!fs
AND @OriginalSize = (SELECT size FROM sysfiles WHERE name = @LogicalFileName) m_rR e\
AND (@OriginalSize * 8 /1024) > @NewSize .e.vh:Sz
BEGIN -- Outer loop. ~ezCE4^&
SELECT @Counter = 0 -<z'f){gb
WHILE ((@Counter < @OriginalSize / 16) AND (@Counter < 50000)) " "a+Nc
BEGIN -- update D{BH~IM
INSERT DummyTrans VALUES ('Fill Log') 4Hzbb#
DELETE DummyTrans ^D4 b\mF
SELECT @Counter = @Counter + 1 =Bo0Oei
END SVq7qc9K?
EXEC (@TruncLog) m}uF&|5
END l'16B^
SELECT 'Final Size of ' + db_name() + ' LOG is ' + =j;o,
J:(
CONVERT(VARCHAR(30),size) + ' 8K pages or ' + iUI,r*
CONVERT(VARCHAR(30),(size*8/1024)) + 'MB' AU'{aC+p
FROM sysfiles K&|zWpb
WHERE name = @LogicalFileName &<UOi@
DROP TABLE DummyTrans I}:>M!w
SET NOCOUNT OFF RB &s$6A
8、说明:更改某个表 ?!~au0
exec sp_changeobjectowner 'tablename','dbo' =:"@YD^a4
9、存储更改全部表 &u=FLp5
CREATE PROCEDURE dbo.User_ChangeObjectOwnerBatch mz\m^g3
@OldOwner as NVARCHAR(128), >MQW{^
@NewOwner as NVARCHAR(128) -IX;r1UD
AS MeplM$9
DECLARE @Name as NVARCHAR(128) {{EQM
+
DECLARE @Owner as NVARCHAR(128) q6_1`Ew
DECLARE @OwnerName as NVARCHAR(128) gu:..'V
DECLARE curObject CURSOR FOR 6@F Z,e
select 'Name' = name, ?N|PgNu X
'Owner' = user_name(uid) @XIwp2A{+
from sysobjects '.kbXw0}
where user_name(uid)=@OldOwner *;gi52tM
order by name R:ar85F
OPEN curObject 7H>dv'
FETCH NEXT FROM curObject INTO @Name, @Owner R2J3R5S=[
WHILE(@@FETCH_STATUS=0) Y(A?ib~K
BEGIN sg6cq_\
if @Owner=@OldOwner X 4/r#<Da
begin IB;y8e,
set @OwnerName = @OldOwner + '.' + rtrim(@Name) \pPq]k
exec sp_changeobjectowner @OwnerName, @NewOwner W}=2?vHV=
end ]iNSa{G
-- select @name,@NewOwner,@OldOwner v#/,,)m
FETCH NEXT FROM curObject INTO @Name, @Owner uPo>?hpq+
END n--`zx-['
close curObject dO8Z {wfs
deallocate curObject X*Q7Yu
GO
w^p2XlQ<
10、SQL SERVER中直接循环写入数据 }Ql;% 7
declare @i int Ahwu'mgnC
set @i=1 Tf[]vqa`G
while @i<30 A6U6SvM;
begin bg=`
insert into test (userid) values(@i) ?b7vc^E&
set @i=@i+1 gTQ6B,`/8
end Xs?>6i@$$
小记存储过程中经常用到的本周,本月,本年函数 rU~"A
Dateadd(wk,datediff(wk,0,getdate()),-1) GYs4#40
Dateadd(wk,datediff(wk,0,getdate()),6) 4%6Q+LS']Q
Dateadd(mm,datediff(mm,0,getdate()),0) 1bDc ct
Dateadd(ms,-3,dateadd(mm,datediff(m,0,getdate())+1,0)) ]D]K_`!K
Dateadd(yy,datediff(yy,0,getdate()),0) v0xi(Wu
Dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate())+1, 0)) g,W#3b6>j
上面的SQL代码只是一个时间段 :-
5Mn3*
Dateadd(wk,datediff(wk,0,getdate()),-1) d8r+UP@#
Dateadd(wk,datediff(wk,0,getdate()),6) \Q)~'P3
就是表示本周时间段. /kWWwy<
下面的SQL的条件部分,就是查询时间段在本周范围内的: < 1r.p<s
Where Time BETWEEN Dateadd(wk,datediff(wk,0,getdate()),-1) AND Dateadd(wk,datediff(wk,0,getdate()),6) LaIif_fie^
而在存储过程中 ){(cRB $
select @begintime = Dateadd(wk,datediff(wk,0,getdate()),-1) Ud9\;Qse
select @endtime = Dateadd(wk,datediff(wk,0,getdate()),6) ]E3g8?L