久久99精品久久久久久琪琪,久久人人爽人人爽人人片亞洲,熟妇人妻无码中文字幕,亚洲精品无码久久久久久久

常用SQL語(yǔ)句 工作兩年總結(jié) 個(gè)個(gè)經(jīng)典 不斷更新

時(shí)間:2019-05-12 07:36:20下載本文作者:會(huì)員上傳
簡(jiǎn)介:寫(xiě)寫(xiě)幫文庫(kù)小編為你整理了多篇相關(guān)的《常用SQL語(yǔ)句 工作兩年總結(jié) 個(gè)個(gè)經(jīng)典 不斷更新》,但愿對(duì)你工作學(xué)習(xí)有幫助,當(dāng)然你在寫(xiě)寫(xiě)幫文庫(kù)還可以找到更多《常用SQL語(yǔ)句 工作兩年總結(jié) 個(gè)個(gè)經(jīng)典 不斷更新》。

第一篇:常用SQL語(yǔ)句 工作兩年總結(jié) 個(gè)個(gè)經(jīng)典 不斷更新

//相同日期,相同商品的sum查詢(xún) SELECT counts.GoodsID,tbg.Name As Name,counts.OutStorageDate As Time, counts.abc FROM(select

sum(Quantity)as abc,GoodsID,OutStorageDate

from tbOhterOutStorage sto ,tbOtherOutStorageDetail std where(sto.OutStorageNo = std.OutStorageNo)group by OutStorageDate,GoodsID)AS counts LEFT JOIN tbGoods tbg ON tbg.ID= counts.GoodsID //相同日期,相同商品的sum查詢(xún)

select t.ID,tbg.Name As Name,t.Time,t.Quantity from tbGoods tbg

left join

(select std.GoodsId As ID,sum(Quantity)as Quantity,sto.InStorageDate as Time

from tbInStorageDetail std

left join tbInStorage sto on sto.InStorageNo=std.InStorageNo group by InStorageDate,GoodsId)as t on t.ID=tbg.ID order by t.Time desc

//庫(kù)存sql 增強(qiáng)版

select vehcName,vehcModel, ISNULL(a.id1,0)as VehicleID , ISNULL(b.snum2,0)as InQuantity, ISNULL(a.snum1,0)as OutQuantity,ISNULL((b.snum2-ISNULL(a.snum1,0)),0)as Quantity from Vehicle FULL JOIN

(select exdeGoodsID as id1,sum(exdeQuantity)as snum1 from ExportDetail group by exdeGoodsID)as a ON Vehicle.ID=a.id1 FULL JOIN

(select imdeGoodsId as id2,sum(imdeQuantity)as snum2 from importDetail group by imdeGoodsID)as b ON a.id1=b.id2 //經(jīng)銷(xiāo)商

注:select saleVehID, count(*)as snum1 from SaleRecord where saleSellerID=1001 group by saleVehID 重點(diǎn)

select vehcName,vehcModel,ISNULL(a.saleVehID,0)as VehicleID , ISNULL(b.snum2,0)as InQuantity, ISNULL(a.snum1,0)as OutQuantity,ISNULL((b.snum2-ISNULL(a.snum1,0)),0)as Quantity from Vehicle LEFT JOIN(select saleVehID, count(*)as snum1 from SaleRecord where saleSellerID=1001 group by saleVehID)as a

ON Vehicle.ID=a.saleVehID LEFT JOIN

(select exdeGoodsID as id2,sum(exdeQuantity)as snum2 from ExportDetail where exdeSupplierID=1001 group by exdeGoodsID)as b ON a.saleVehID=b.id2 order by Quantity asc

入庫(kù)-出庫(kù)=庫(kù)存(供貨商的算法)

select exdeGoodsID as 編號(hào),innum as 入庫(kù),outnum as 出庫(kù),a.innum-b.outnum as 庫(kù)存 from

(select sum(imdeQuantity)as innum,imdeGoodsID from ImportDetail Group By imdeGoodsID)as a LEFT JOIN(select sum(exdeQuantity)as outnum,exdeGoodsID from ExportDetail Group By exdeGoodsID)as b ON imdeGoodsID=exdeGoodsID 入庫(kù)-出庫(kù)=庫(kù)存(門(mén)店的算法)

select a.imdeGoodsID as 編號(hào),a.innum as 入庫(kù),b.outnum as 出庫(kù),a.innum-b.outnum as 庫(kù)存 from

(select sum(imdeQuantity)as innum,imdeGoodsID from ImportDetail Group By imdeGoodsID)as a LEFT JOIN(select count(*)as outnum,saleVehID from SaleRecord group by saleVehID)as b ON a.imdeGoodsID=b.saleVehID

//求一段字符串的第幾位

declare @string_aa varchar(20)set @string_aa =(select CustBirth from customer where ID=1009)select substring(@string_aa,1,4)as 年 //獲取日期的某個(gè)位置的值

declare @string_aa varchar(20)set @string_aa =convert(char(10), getdate(),120)select substring(@string_aa,1,4)as 年 //獲取當(dāng)前時(shí)間,各種格式的轉(zhuǎn)變

select convert(char, getdate(), 101),//04/08/2011

convert(char, getdate(), 1),//04/08/11

convert(char, getdate(), 112),//20110408

convert(varchar(10), getdate(),120)

//2011-04-08

convert(varchar, getdate(),120)

//2011-04-08 15:43:36

select convert(varchar(12), getdate(), 111)2004/09/12 select convert(varchar(12), getdate(), 112)20040912 select convert(varchar(12), getdate(), 102)2004.09.12 select convert(varchar(12), getdate(), 101)09/12/2004 select convert(varchar(12), getdate(), 103)12/09/2004 select convert(varchar(12), getdate(), 104)12.09.2004 select convert(varchar(12), getdate(), 105)12-09-2004 select convert(varchar(12), getdate(), 106)12 09 2004 select convert(varchar(12), getdate(), 107)09 12, 2004 select convert(varchar(12), getdate(), 108)11:06:08 select convert(varchar(12), getdate(), 109)09 12 2004 1 select convert(varchar(12), getdate(), 110)09-12-2004 select convert(varchar(12), getdate(), 113)12 09 2004 1 select convert(varchar(12), getdate(), 114)11:06:08.177

//datetime類(lèi)型的數(shù)據(jù),求它的年,月,日

select month(CustBirth)as m,year(CustBirth)as y from customer where ID=1009 select month(getdate())as m ,year(getdate())as y

select sin(23.45),atan(1.234),rand(),PI(),sign(2.34)--其中rand是獲得一個(gè)隨機(jī)數(shù)

--時(shí)間函數(shù)

select getdate()as 'wawa_getdate'--當(dāng)前時(shí)間

select getutcdate()as 'wawa_getutcdate'--獲取utc時(shí)間

select day(getdate())as 'wawa_day'--取出天

select month(getdate())as 'wawa_month'--取出月

select year(getdate())as 'wawa_year'--取出年

select dateadd(d,3,getdate())as 'wawa_dateadd'--加三天,注意'd'表示天,'m'表示月,'yy'表示年,下面一樣

select dateadd(m,3,getdate())as 'wawa_dateadd' select dateadd(yy,3,getdate())as 'wawa_dateadd'

select datediff(m,'2004-07-01','2004-09-15')as 'wawa_datediff'--計(jì)算兩個(gè)時(shí)間的差

select datediff(d,'2004-07-01','2004-09-15')as 'wawa_datediff' select datediff(yy,'2004-07-01','2009-07-15')as 'wawa_datediff' select datenamselect datepart(d,getdate())as 'wawa_datepart' select datename(weekday, getdate())e(d,'2004-07-15')as 'wawa_datename'--取出時(shí)間的某一部分

select datename(m,'2004-07-15')as 'wawa_datename' select datename(yy,'2004-07-15')as 'wawa_datename' select datepart(d,getdate())as 'wawa_datepart' select datepart(m,getdate())as 'wawa_datepart' select datepart(yy,getdate())as 'wawa_datepart'--取出時(shí)間的某一部分,和上面的那個(gè)差不多

--datename 返回代表指定日期的指定日期部分的字符串 select datename(weekday, getdate())--返回:星期五

use test go create table worker(id int identity(1,1)primary key, wName varchar(30)not null, Sex char(2)not null, position varchar(30)null, birthday datetime not null,)

alter table worker add salary money--創(chuàng)建學(xué)生表 use chenxian go create table t_student(sid int identity(1,1)primary key,--編號(hào)

sname varchar(20)not null,--姓名

age int not null--年齡)drop table t_student select * from t_student--插入數(shù)據(jù)

insert into t_student values('qiujialong','21');--select....into....select sname,age into newtable from t_student select * from t_student bulk insert chenxian.dbo.t_student from 'd:tempa.txt' with(FIELDTERMINATOR='|',--分割

ROWTERMINATOR='n'--識(shí)別)

insert into t_mm values('qiujialong','21');use chenxian go create table t_mm(sid int identity(1,1)primary key,--編號(hào)

sname varchar(20)not null,--姓名

age int not null--年齡)--更新

update t_mm set age =age*2 update t_mm set sname='你退休了' where age=84----sid=1 select * from t_mm insert into t_mm values('xiaos','20');--把年齡最小的人的姓名改成?你最小?

update t_mm set sname='你最小' where age=(select min(age)from t_mm);select * from t_mm select age,sname from t_mm select '姓名',sname,'年齡',age from t_mm--添加中文 select '姓名'=sname,'年齡'=age from t_mm select sname as '姓名',age as '年齡' from t_mm select age=age*2 from t_mm--查詢(xún)不更新數(shù)據(jù) select age from t_mm

select pi()as '圓周率' create table t_kk(id int identity(1,1)primary key, sname varchar(20)not null)insert into t_kk values('lixin');select * from t_kk select '姓名' = upper(sname)from t_kk select upper(sname)as '姓名' from t_kk

--過(guò)濾重復(fù)

select * from newtable update newtable set age='22' where sname='qiujialong' select all age from newtable select distinct age from newtable--從小到大過(guò)濾重復(fù)

delete from newtable--只刪除數(shù)據(jù) select * from t_student delete * from t_student--錯(cuò)

update t_mm set sname='你最小' where age=(select min(age)from t_mm);delete from t_student where age=(select max(age)from t_student);select * from t_student

use chenxian go create table t_student(sid int primary key identity(1,1), sname varchar(30)not null, age int not null, sex char(2)not null, mark int null)--插入數(shù)據(jù)

insert into t_student values('linxin','30','男','60');insert into t_student values('wujin','21','男','90');insert into t_student values('zhangwen','20','女','96');insert into t_student values('linhua','22','男','70');select * from t_student--查詢(xún)分?jǐn)?shù)最高的人名

select sname from t_student where mark=(select max(mark)from t_student);--刪除sid=1 delete from t_student where sid =1--排序

select * from t_student select * from t_student order by age asc order by age asc--升序 order by age desc--降序

select * from t_student order by age--默認(rèn)升序 select * from t_student order by mark--默認(rèn)升序

--top select top(2)* from t_student select top(2)sname,age from t_student delete top(1)from t_student select top(50)percent * from t_student select * from t_student--函數(shù),模糊搜索

select * from t_student where age >=30 select * from t_student where sex='男' select * from t_student where sname like '%xin' select * from t_student where sname like '%J%'

insert into t_student values('向華強(qiáng)','32','男','69')select * from t_student where sname like '_華強(qiáng)' select * from t_student select * from t_student where sname like '[lz]%' select * from t_student where sname like '%[lz]'--也有位置限制 insert into t_student values('lena','34','男','99')select * from t_student where sname like 'l[^i]%' insert into t_student values('%紅','44','男','80')insert into t_student values('hh','44','男','80')select * from t_student where sname like '%/%%' escape'/' select * from t_student where sname like '[%]紅'--and ,or,in()select * from t_student where age ='30' select * from t_student where age ='30' or age ='21' select * from t_student where age ='30' and sname='linxin' select * from t_student where age in('30')--速度比=快 select * from t_student where age in('30','21')select * from t_student where age!='30' and sname!= 'linxin' select * from t_student where not(age ='30' and sname='linxin')select * from t_student where not(age ='20' or sname='linxin')select * from t_student where age not in('30','21')select * from t_student where mark >='80' and mark<='100' select * from t_student where mark between '80' and '100'--包括80,100 select * from t_student--count use master go select count(*)from spt_values--數(shù)據(jù)總條數(shù) select * from spt_values use chenxian go insert into t_student values('linxin','34','男','99')--篩選重復(fù)項(xiàng)

select count(distinct sname)from t_student select count(*)from t_student select * from t_student--升序并且計(jì)算總分 select sname,age,mark from t_student order by mark compute sum(mark)

use chenxian go create table t_order(oid int identity(1,1)primary key, odate datetime not null, oprice money null, oname varchar(32)not null)insert into t_order values('2009/08/09','30','lixin');insert into t_order values('2009/08/21','44','lixin');insert into t_order values('2009/08/28','38','xujuan');insert into t_order values('2009/09/28','55','xuli');

select * from t_order--把相同人名的數(shù)據(jù)向加(分組技術(shù))select oname , sum(oprice)from t_order group by oname---建立一個(gè)chenxian的數(shù)據(jù)庫(kù) create database chenxian use chenxian go create table

t_student(xid

int identity(1,1)primary key ,--學(xué)號(hào)

xname varchar(20)not null,--學(xué)生姓名

xage

int not null,--學(xué)生年齡

xsex

char(2),--學(xué)生性別

xcj

int

--學(xué)生成績(jī))--類(lèi)型轉(zhuǎn)換函數(shù)

select * from

t_student where cast(xage as char(2))exec sp_help t_student select '101'=convert(char, getdate(), 101), '1'=convert(char, getdate(), 1),--與101相同 '112'=convert(char, getdate(), 112)

--插入數(shù)據(jù)

insert into

t_student values('lixin','30','男','60');insert into

t_student values('wujing','21','男','90');insert into

t_student values('zhangwen','22','女','96');insert into

t_student values('lihua','22','女','80');select * from t_student

= '30'

--排序

select

* from

t_student

order by xage asc--根據(jù)年齡 升序 select

* from

t_student order by xage desc--降序--默認(rèn)升序

select

*

from

t_student order by xage

--查看數(shù)據(jù)

select top(2)*

from

t_student select top(1)percent * from t_student select top(20)percent * from t_student select top(30)percent * from t_student--再插入一條數(shù)據(jù)

insert into

t_student values('lihua','22','女','80');

----百分比的使用 use AdventureWorks go select top(1)percent name,productnumber,standardcost,listprice,safetystocklevel,reorderpoint from Production.product order by standardcost desc use AdventureWorks go select top(1)percent with ties name,productnumber,standardcost,listprice,safetystocklevel,reorderpoint from Production.product order by standardcost desc

---條件語(yǔ)句 use chenxian go select

*

from

t_student where xage > = 30 select

*

from

t_student

where xname

like 'li%'--返回以li開(kāi)頭的姓名 select

*

from

t_student

where xname like '%xin'--返回以xin結(jié)束的姓名 select

*

from

t_student where xname

like '%g%'

--包含g的姓名 insert into

t_student

values('向華強(qiáng)','32','男','80');select

*

from t_student where xname

like '_hangwen'

--返回以這兩個(gè)字符ng結(jié)束

select

*

from t_student where xname

like '_華強(qiáng)'

--返回以這兩個(gè)字符ng結(jié)束

select

*

from t_student where xname like '[lz]%'

--返回以l或z開(kāi)頭的姓名 select

* from t_student where

xname

like '[l-向]華強(qiáng)'--l-向,華強(qiáng)結(jié)束的三個(gè)字符

insert into

t_student

values('lenkai','30','男','80');select

* from

t_student where xname like

'l[^i]%'--返回以l開(kāi)始,第二個(gè)字符不是i 的任意字符--escape語(yǔ)法

insert into

t_student values('%星','1','女','4');SELECT * FROM t_student where xname like '%/%%' ESCAPE '/'--符合搜索條件

select

*

from

t_student--in,not語(yǔ)句

select

*

from

t_student

where

xage

in

('30');select

*

from

t_student

where

xage

not

in

('30');--and語(yǔ)句

select

* from

t_student where

xage = 30 and xname ='lixin';select

* from

t_student where

not(xage = 30 and xname ='lixin');---or 語(yǔ)句

select

*

from t_student where xname = 'lixin' or xage > 23--模糊搜索與and語(yǔ)句

select

*

from

t_student where

xname like 'li%' and xage =30

--between

and 語(yǔ)句的使用

select

*

from

t_student where

xcj > = 80 and xcj < = 100 select

*

from

t_student where

xcj

between

and 100--聚合技術(shù)

select count(*)

from

t_student select count(distinct

xname)

from

t_student

--compute select

xname ,xage ,xcj from t_student order by xcj compute sum(xage),max(xage)--按成績(jī)排序

-----------------普通分組技術(shù)--建立一張訂單表 create table t_order(oid int

identity(1,1)primary key,orderdate

datetime,price

money,customer varchar(20))insert into t_order values('2008/12/27','20','lixin');insert into t_order values('2008/12/06','10','lixin');insert into t_order values('2008/12/27','30','劉國(guó)棟');insert into t_order values('2008/12/06','40','劉國(guó)棟');

--分組查詢(xún)

select customer ,sum(price)from t_order group by customer

select customer,sum(price)

from t_order group by customer

having sum(price)>60 select customer,sum(price)

from t_order group by customer

having sum(price)>10 order by sum(price)desc use chenxian go select customer ,'消費(fèi)金額'= sum(price)

from t_order group by customer select customer ,'消費(fèi)金額'= sum(price)

from t_order group by customer with rollup--得到各組的單項(xiàng)組合

select customer ,'消費(fèi)金額'= sum(price)

from t_order group by customer with cube--得到各組之間的任意組合--建立一張銷(xiāo)售表 create table t_invert(id

int identity(1,1)primary

key ,itemname

varchar(20),color varchar(10),quantity int)insert into t_invert values('汽車(chē)','白色','69');insert into t_invert values('摩托車(chē)','紅色','62');insert into t_invert values('自行車(chē)','紅色','100');insert into t_invert values('摩托車(chē)','黑色','170');insert into t_invert values('自行車(chē)','黑色','85');select itemname ,color ,'數(shù)量'=sum(quantity)from t_invert group by itemname,color select itemname ,color ,'數(shù)量'=sum(quantity)from t_invert group by itemname,color with rollup select itemname ,color ,'數(shù)量'=sum(quantity)from t_invert group by itemname,color with cube-----------------------select convert(varchar(12), getdate(), 111)2004/09/12 select convert(varchar(12), getdate(), 112)20040912 select convert(varchar(12), getdate(), 102)2004.09.12 select convert(varchar(12), getdate(), 101)09/12/2004 select convert(varchar(12), getdate(), 103)12/09/2004 select convert(varchar(12), getdate(), 104)12.09.2004 select convert(varchar(12), getdate(), 105)12-09-2004 select convert(varchar(12), getdate(), 106)12 09 2004 select convert(varchar(12), getdate(), 107)09 12, 2004 select convert(varchar(12), getdate(), 108)11:06:08 select convert(varchar(12), getdate(), 109)09 12 2004 1 select convert(varchar(12), getdate(), 110)09-12-2004 select convert(varchar(12), getdate(), 113)12 09 2004 1 select convert(varchar(12), getdate(), 114)11:06:08.177

--連接技術(shù)--交叉連接 use

chenxian go create table

t_a(id

int identity(1,1)primary key,aname varchar(20))

create table t_b(id

int identity(1,1)primary key,bname varchar(20))--插入數(shù)據(jù)

insert

into

t_a

values('lixin');insert

into

t_a

values('weicheng');insert into t_b values('計(jì)算機(jī)系');insert into t_b values('數(shù)學(xué)系系');select

*

from

t_a select

*

from

t_b

---交叉連接

select a.id ,a.aname,b.bname from

t_a as a cross join t_b as select a.id ,aname,bname from

t_a a cross join t_b b--其中注意的是id是兩個(gè)表都有,必須明確的指明屬于哪個(gè)表的ID。--as是這個(gè)表的別名,可以取消as寫(xiě)法--把表a的值分別給表b select *

from

t_a ,t_b select *

from t_a

b--創(chuàng)建一張老師表 use chenxian go create table t_teacher(id

int

identity(1,1)primary key,--自增長(zhǎng),從1開(kāi)始,每次步進(jìn)1;

tname

varchar(20),password varchar(10),age

int)--插入數(shù)據(jù) ,注意這里沒(méi)有顯示的插入ID值

insert into

t_teacher values('lixin','123456','30');insert into

t_teacher values('wujing','654321','21');insert into

t_teacher values('yangfeng','654321','18');insert into

t_teacher values('minglei','778899','22');select

*

from

t_teacher--建立一張班級(jí)表--建立一個(gè)班級(jí)表 create

table t_class(id int

identity(1,1)primary key,cname varchar(20),caddress varchar(20),tid

int)insert into t_class values('成賢1班','光輝樓','2');insert into t_class values('成賢2班','晨練樓','1');insert into t_class values('成賢3班','飛天樓','4');insert into t_class values('成賢4班','朝露樓','3');select

*

from

t_teacher select

*

from t_class---內(nèi)連接

select

*

from

t_teacher a inner join

t_class---外連接1)左連接 2)右連接 3)全連接---建立一張政黨表,義員表 create table t_party(code

int

primary key,--政黨代碼

sname varchar(20),--政黨名稱(chēng)

leader varchar(10)

--政黨領(lǐng)袖)--插入數(shù)據(jù)

insert into t_party values('1','人民民主黨','李欣');insert into t_party values('2','人民共和黨','明磊');

b on a.id=b.tid insert into t_party values('3','人民共產(chǎn)黨','武警');insert into t_party values('4','人民勞動(dòng)黨',NULL);insert into t_party values('6','黑手黨','阿里');delete from t_party--全刪 select * from t_party--建立一張議員表 use chenxian go create table t_msp(id

int primary key ,--議員編號(hào)

mname varchar(50),--議員名稱(chēng)

party int ,--議員所在的政黨的代碼

constituency varchar(20)--所在選區(qū))insert into t_msp values('1','lihua','4','英國(guó)3區(qū)');insert into t_msp values('2','dongqinbei','3','英國(guó)2區(qū)');insert into t_msp values('3','shenbowen','2','英國(guó)1區(qū)');insert into t_msp values('4','wangliang','1','英國(guó)0區(qū)');insert into t_msp values('5','zhangwen',NULL,'英國(guó)0區(qū)');delete from t_msp--下面的語(yǔ)句選出沒(méi)有領(lǐng)導(dǎo)者的政黨

select code,sname from t_party where leader is NULL--一個(gè)議員被開(kāi)除出黨,看看他是誰(shuí)。(即該議員的政黨為空值)select

*

from t_msp

where party is NULL--left join(左連接)包含所有的左邊表中的記錄甚至是右邊表中沒(méi)有和它匹配的記錄。--同理,也存在著相同道理的 right join(右連接),即包含所有的右邊表中的記錄甚至是左邊表中沒(méi)有和它匹配的記錄。

--而full join(全連接)顧名思義,左右表中所有記錄都會(huì)選出來(lái)。--看看具體的人屬于哪個(gè)政黨,他的領(lǐng)導(dǎo)者是誰(shuí)?

select

*

from

t_msp m inner join t_party p

on m.code = p.party

--很遺憾,我們發(fā)現(xiàn)該查詢(xún)的結(jié)果少了個(gè)議員:zhangwen。

--為什么,因?yàn)檫@個(gè)議員不屬于任和政黨,即他們的政黨字段(Party)為空值。--那么為什么不屬于任何政黨就查不出來(lái)了?這是因?yàn)榭罩翟谧鞴帧?/p>

--因?yàn)樽h員表中政黨字段(Party)的空值在政黨表中找不到對(duì)應(yīng)的記錄作匹配,--即FROM msp JOIN party ON party=code 沒(méi)有把該記錄連接起來(lái),而是過(guò)濾出去了。--在該短語(yǔ)中,msp在Join的左邊,所有稱(chēng)為左表。party在Join的右邊,所有稱(chēng)為右表--Ok,現(xiàn)在再看看這句話,“包含所有的左邊表中的記錄甚至是右邊表中沒(méi)有和它匹配的記錄”,--意思應(yīng)該很明白了吧。執(zhí)行下面這個(gè)語(yǔ)句,那兩個(gè)沒(méi)有政黨的議員就漏不了了 select m.mname, p.sname from t_msp m left outer join t_party p on m.party=p.code

--關(guān)于右連接,看看這個(gè)查詢(xún)就明白了: select m.mname, p.sname from t_msp m right join t_party p on m.party=p.code--這個(gè)查詢(xún)的結(jié)果列出所有的議員和政黨,包含沒(méi)有議員的政黨,但不包含沒(méi)有政黨的議員。--那么既要包含沒(méi)有議員的政黨,又要包含沒(méi)有政黨的議員該怎么辦呢,對(duì)了,全連接(full join)。

select m.mname, p.sname from t_msp m full join t_party p on m.party=p.code

---子查詢(xún)

---建立一張學(xué)生表 create table t_stu(id

int identity(1,1)primary key,sname varchar(20),xh

varchar(10)

--系號(hào))insert into

t_stu values('lixin','2');insert into

t_stu values('文文','3');insert into

t_stu values('王意','3');select

* from t_stu--子查詢(xún) 和文文在同一個(gè)系的

SELECT * FROM t_stu where xh =(select xh from t_stu where sname ='文文')SELECT * FROM t_stu where xh!=(select xh from t_stu where sname ='文文')

--exists select *

from t_stu where exists(select 1)select *

from t_stu where exists(select xh

from

t_stu where select *

from t_stu where exists(select xh

from

t_stu where

---建立一張t_a1,t_b1,union關(guān)鍵字 create table t_a1(t1 int identity(1,1)primary key,aname varchar(20),aage

int)create table t_b1(t2 int identity(1,1)primary key,bname varchar(20),bage int)drop table t_a1 drop table t_b1 insert into t_a1 values('lixin1','1');

sname ='lixin')sname ='lihua')insert into t_a1 values('lixin2','2');insert into t_a1 values('lixin3','3');insert into t_b1 values('wenwen','2');insert into t_b1 values('wenwen','5');

select * from t_a1--按表來(lái) union all select * from t_b1 select * from t_a1--按id來(lái) union

select * from t_b1 select password from t_teacher union

select cname from t_class--過(guò)濾重復(fù)數(shù)據(jù) select password from t_teacher union all

select cname from t_class--不過(guò)濾重復(fù)數(shù)據(jù)

--except運(yùn)算符從左查詢(xún)中返回右查詢(xún)中沒(méi)有的值

select aage

from t_a1 except select bage from t_b1--intersect運(yùn)算符則返回左右兩個(gè)查詢(xún)語(yǔ)句都包含的所有重復(fù)值 select aage

from t_a1 intersect select bage

from t_b1

--公用表達(dá)式

use AdventureWorks go with AmountOrder(SalesPersonID,personcount,MaxDate)as(select salesPersonID,count(*),max(orderdate)

from sales.salesorderheader

where salespersonid is not null

group by SalesPersonID)select

SalesPersonID, personcount, MaxDate from AmountOrder

order by SalesPersonID

--pivot 和 unpivot USE AdventureWorks;GO SELECT VendorID, [164], [198] , [223] , [231] , [233] FROM

(SELECT PurchaseOrderID, EmployeeID, VendorID FROM Purchasing.PurchaseOrderHeader)as p PIVOT(COUNT(PurchaseOrderID)FOR EmployeeID IN([164], [198], [223], [231], [233]))AS pvt ORDER BY VendorID----分析

select

PurchaseOrderID

from

Purchasing.PurchaseOrderHeader CREATE TABLE pvt(VendorID int, Emp1 int, Emp2 int, Emp3 int, Emp4 int, Emp5 int)GO INSERT INTO pvt VALUES(1,4,3,5,4,4)INSERT INTO pvt VALUES(2,4,1,5,5,5)INSERT INTO pvt VALUES(3,4,3,5,4,4)INSERT INTO pvt VALUES(4,4,2,5,5,4)INSERT INTO pvt VALUES(5,5,1,5,5,5)GO--Unpivot the table.SELECT VendorID, Employee, Orders FROM

(SELECT VendorID, Emp1, Emp2, Emp3, Emp4, Emp5

FROM pvt)p UNPIVOT

(Orders FOR Employee IN

(Emp1, Emp2, Emp3, Emp4, Emp5))AS unpvt GO

--加密表中數(shù)據(jù)

create database encryption go use encryption go--建立主密鑰

create master key encryption

by password='23987hxJ#KL95234nl0zBe'--建立證書(shū)

create certificate xxxSystemCertificate with subject='xxx system certificate', start_date='12-12-2008'--建立對(duì)稱(chēng)密鑰

create symmetric key xxxSystemSymmetric with algorithm= des--aes_256 encryption BY certificate xxxSystemCertificate CREATE TABLE employee(id int identity primary key, e_name varchar(30)null, pwd varchar(128)null)open symmetric key xxxSystemSymmetric decryption by certificate xxxSystemCertificate insert into employee(e_name,pwd)values('li',EncryptByKey(key_guid('xxxSystemSymmetric'),'66'))go--解密函數(shù)

select e_name, CONVERT(varchar, DecryptByKey(pwd))from employee select

pwd from

employee delete from employee

--查詢(xún)選修了課程的人數(shù)

select count(distinct cno)from t_cj--查詢(xún)沒(méi)有選修了張亞勤老師的學(xué)生

select sname from t_stu where sno not in(select sno from t_cj where cno in(select cno from t_kc where cteacher ='張亞勤'))

--創(chuàng)建視圖

create view v_tc3

as select cname,cteacher from t_kc c inner join t_cj t on c.cno=t.cno select * from v_tc3--查看視圖的定義文本 sp_helptext v_tc3

--加密視圖文本

create view v_stu with encryption as select * from t_stu sp_helptext v_stu alter table t_stu add phone varchar(20)select * from t_stu select * from v_stu--修改跟新視圖

alter view v_stu as select * from t_stu--重命名

sp_rename v_stu ,v_t select * from v_t--顯示視圖的特性 sp_help v_t drop view v_t create table t_employes(number int identity(1,1)primary key,ename varchar(20),age int ,salary money)create view v_emp as select ename,age ,salary from t_employes insert into v_emp values('lixin','30','3000');select * from v_emp select * from t_employes create view v_employes as select ename,age ,salary from t_employes where ename='lixin'--存儲(chǔ)查詢(xún)語(yǔ)句而不是存儲(chǔ)語(yǔ)句

insert into v_employes values('haha','23','3000');select * from v_employes--限制條件的視圖

create view v_employes as select ename,age ,salary from t_employes where salary>'1000' create view v_employes1 as select ename,age ,salary from t_employes where salary>'1000' with check option--插不進(jìn)去,表里也不會(huì)有數(shù)據(jù) update v_employes set salary= salary+10 delete from v_employes where number='2'

use test go create table t_employees(id

int identity primary key,ename varchar(20),age

int,price money)--插入數(shù)據(jù)

insert into t_employees

values('李欣','30','8000');insert into t_employees

values('馬鵬杰','22','6000');insert into t_employees

values('武警','21','7000');insert into t_employees

values('曹恒業(yè)','20','7500');insert into t_employees

values('顧麗','18','7400');--平均數(shù)

select '平均工資' = avg(price)from t_employees declare @price money set @price =(select avg(price)from t_employees)select @price--工資最高的

select

max(price)

from t_employees declare @price money set @price =(select max(price)from t_employees)select @price--工資最低的

select min(price)

from t_employees declare @price money set @price =(select min(price)from t_employees)select @price--工資總和

select sum(price)

from t_employees declare @price money set @price =(select sum(price)from t_employees)select @price--求個(gè)數(shù),有多少名員工

select

count(*)

from t_employees declare @id int set @id =(select count(id)from t_employees)select @id as '員工個(gè)數(shù)'--配置函數(shù)

SELECT @@version--獲取當(dāng)前數(shù)據(jù)庫(kù)版本

SELECT @@language--當(dāng)前語(yǔ)言--數(shù)學(xué)函數(shù)

select sin(23.45),atan(1.234),rand(),PI(),sign(2.34)--其中rand是獲得一個(gè)隨機(jī)數(shù)

--時(shí)間函數(shù)

select getdate()as 'wawa_getdate'--當(dāng)前時(shí)間

select getutcdate()as 'wawa_getutcdate'--獲取utc時(shí)間

select day(getdate())as 'wawa_day'--取出天

select month(getdate())as 'wawa_month'--取出月

select year(getdate())as 'wawa_year'--取出年

select dateadd(d,3,getdate())as 'wawa_dateadd'--加三天,注意'd'表示天,'m'表示月,'yy'表示年,下面一樣

select dateadd(m,3,getdate())as 'wawa_dateadd' select dateadd(yy,3,getdate())as 'wawa_dateadd'

select datediff(m,'2004-07-01','2004-09-15')as 'wawa_datediff'--計(jì)算兩個(gè)時(shí)間的差

select datediff(d,'2004-07-01','2004-09-15')as 'wawa_datediff' select datediff(yy,'2004-07-01','2009-07-15')as 'wawa_datediff' select datename(d,'2004-07-15')as 'wawa_datename'--取出時(shí)間的某一部分

select datename(m,'2004-07-15')as 'wawa_datename' select datename(yy,'2004-07-15')as 'wawa_datename' select datepart(d,getdate())as 'wawa_datepart' select datepart(m,getdate())as 'wawa_datepart' select datepart(yy,getdate())as 'wawa_datepart'

--取出時(shí)間的某一部分,和上面的那個(gè)差不多

--datename 返回代表指定日期的指定日期部分的字符串 select datename(weekday, getdate())--返回:星期五--系統(tǒng)函數(shù)

use test go

select host_name()as 'host_name',host_id()as 'host_id',user_name()as 'user_name',user_id()as 'user_id',db_name()as 'db_name'--(1)字符串函數(shù)

--使用 LTRIM 函數(shù)刪除字符變量中的起始空格。--程序清單如下:

DECLARE @string_to_trim varchar(60)SET @string_to_trim = '

Five spaces are at the beginning of this

string.' SELECT 'Here is the string without the leading spaces: ' + ltrim(@string_to_trim)

DECLARE @string_to_trim varchar(60)SET @string_to_trim = '

Five spaces are at the beginning of this string.' SELECT 'Here is the string without the leading spaces: ' + rtrim(@string_to_trim)--upper declare @string_aa varchar(20)set @string_aa ='abcd' select upper(@string_aa);--lower declare @string_aa varchar(20)set @string_aa ='DBDB' select lower(@string_aa);--charindex declare @string_aa varchar(20)--查出字母在短語(yǔ)里的位數(shù) set @string_aa ='ABC' select charindex('B',@string_aa);--datalength declare @string_aa varchar(20)--查出短語(yǔ)的長(zhǎng)度 set @string_aa ='ABC' select datalength(@string_aa);--substring declare @string_aa varchar(20)--從2開(kāi)始一共有4位長(zhǎng)度 set @string_aa ='ABCDEFG' select substring(@string_aa,2,4);--在第一個(gè)字符串(abcdef)中刪除從第二個(gè)位置(字符 b)開(kāi)始的三個(gè)字符,--然后在刪除的起始位置插入第二個(gè)字符串,創(chuàng)建并返回一個(gè)字符串。--程序清單如下:

SELECT stuff('abcdef', 2, 3, 'ijklmn')--str轉(zhuǎn)換

declare @string_aa float--符號(hào)類(lèi)型轉(zhuǎn)換 set @string_aa ='33.333' select str(@string_aa);/* 字符串函數(shù) */

/* 返回字符表達(dá)式中最左側(cè)字符的ASCII代碼值 */

select Ascii('abc')--a:97,A:65

/* 將整數(shù)ASCII代碼轉(zhuǎn)換為字符 */

select Char(65)--97:a,65:A

/* 返回表達(dá)式中指定字符的開(kāi)始位置 查找是否包含,返回第一次出現(xiàn)的位置,沒(méi)有,返回0 */

select charindex('c','abcdefgb')--3

查詢(xún)c所在字符串的位置。

/* 以整數(shù)返回兩個(gè)字符表達(dá)式的SOUNDEX值之差 */

select difference('bet','bit')--3

select difference('bitas','bitas')--一樣是4,數(shù)字越低相似度越低

/* 返回字符表達(dá)式最左側(cè)指定數(shù)目的字符 */

select Left('abcdefg',3)--abc

select right('abcdefg',3)/* 返回給定字符串表達(dá)的字符數(shù) */

select Len('abcdefg')--7

/* 返回將大寫(xiě)字符轉(zhuǎn)換為小字符的字符表達(dá)式 */

select Lower('ABCDEFG')--abcdefg

select upper('abcdefg ')--ABCDEFG

/* 返回刪除了前導(dǎo)空格之后字符表達(dá)式 */

select Ltrim(' abcdefg')--abcdefg

/* 返回刪除了后導(dǎo)空格之后字符表達(dá)式 */

select Rtrim('abcdefg ')--abcdefg

/* 返回具有給定的整數(shù)代碼的UNICODE字符 */

select Nchar(65)--A

/* 返回指定表達(dá)式中模式第一次出現(xiàn)的開(kāi)始位置 */

select patindex('%_cd%','abcdefg')--2

/* 返回為成為有效的SQL SERVER分隔標(biāo)識(shí)符而添加了分隔符的UNICODE字符串 */

select quotename('create table')--寫(xiě)出字符串文本

/* 用第三個(gè)表達(dá)式替換第一個(gè)表達(dá)式中出現(xiàn)的第二個(gè)表達(dá)式 */

select replace('abcdefg','cd','xxx')--abxxxefg

/* 按指定次數(shù)重復(fù)表達(dá)式 */

select replicate('abc|',4)--abc|abc|abc|abc|

/* 返回字符表達(dá)式的逆向表達(dá)式 */

select reverse('abc')--cba

/* 返回字符表達(dá)式右側(cè)指定數(shù)目的字符 */

select Right('abcd',3)--bcd

/* 返回字符表達(dá)式左側(cè)指定數(shù)目的字符 */

select left('abcd',3)--abc

/* 返回截?cái)嗔怂形搽S空格之后的字符表達(dá)式 */

select Rtrim('abcd

')--abcd

/* 刪除指定長(zhǎng)度的字符,并在指定的起點(diǎn)處插入另一組字符 */

select stuff('abcdefg',2,4,'xxx')--axxxfg

/* 返回字符表達(dá)式,二進(jìn)制,文本表達(dá)式或圖像表達(dá)的一部分 */

select substring('abcdefg',2,3)--bcd

/* 返回表達(dá)第一個(gè)字符的UNICODE整數(shù)值 */

select Unicode('a')--97

/* 返回將小寫(xiě)字符轉(zhuǎn)換為大寫(xiě)字符的字符表達(dá)式 */

select Upper('a')--'A'

select Str(14.4444,5)--[14.44]--從左往右一共的位數(shù),包括小數(shù)點(diǎn)

--小數(shù)點(diǎn)右側(cè)的數(shù)字位數(shù),decimal 參數(shù)必須是一種可以隱式轉(zhuǎn)換為 int 的數(shù)據(jù)類(lèi)型。默認(rèn)值為 0。--排名函數(shù)

--這個(gè)函數(shù)的功能是為查詢(xún)出來(lái)的每一行記錄生成一個(gè)序號(hào)。--其中row_number列是由row_number函數(shù)生成的序號(hào)列。

--在使用row_number函數(shù)時(shí)要使用over子句選擇對(duì)某一列進(jìn)行排序,然后才能生成序號(hào)。select row_number()over(order by age)as '序號(hào)' ,* from t_employees

--再插入數(shù)據(jù)

insert into t_employees

values('顧麗1','18','7400');insert into t_employees

values('顧麗2','18','7400');--如果使用rank函數(shù)來(lái)生成序號(hào),這3條記錄的序號(hào)是 的,--而第4條記錄會(huì)根據(jù)當(dāng)前的記錄數(shù)生成序號(hào),后面的記錄依此類(lèi)推,也就是說(shuō),在這個(gè)例子中,第4條記錄的序號(hào)是4,而不是2。

select rank()over(order by age),* from t_employees--dense_rank函數(shù)的功能與rank函數(shù)類(lèi)似,只是在生成序號(hào)時(shí)是連續(xù)的,--而rank函數(shù)生成的序號(hào)有可能不連續(xù)。如上面的例子中如果使用dense_rank函數(shù),第4條記錄的序號(hào)應(yīng)該是2,而不是4。

select dense_rank()over(order by age),* from t_employees--ntile函數(shù)可以對(duì)序號(hào)進(jìn)行分組處理。這就相當(dāng)于將查詢(xún)出來(lái)的記錄集放到指定長(zhǎng)度的數(shù)組中,--每一個(gè)數(shù)組元素存放一定數(shù)量的記錄。ntile函數(shù)為每條記錄生成的序號(hào)就是這條記錄所有的數(shù)組元素的索引(從1開(kāi)始)。

--也可以將每一個(gè)分配記錄的數(shù)組元素稱(chēng)為“桶”

select ntile(4)over(order by age)as '桶',* from t_employees select charindex('123','abc123def')--返回字符串中指定表達(dá)式的起始位置

select quotename('abc','}'), quotename('abc'), quotename('abc','()'), quotename('abc','<')--返回由指定字符擴(kuò)住的字符串

select reverse('abc'),reverse('上海')--顛倒字符串順序

select replace('abcdefghicde','cde','xxxx')--返回唄替換了指定子串的字符串

select space(5),space(-2)

第二篇:SQL語(yǔ)句經(jīng)典總結(jié)

SQL語(yǔ)句經(jīng)典總結(jié)

一、入門(mén)

1、說(shuō)明:創(chuàng)建數(shù)據(jù)庫(kù)

CREATE DATABASE database-name2、說(shuō)明:刪除數(shù)據(jù)庫(kù) drop database dbname

3、說(shuō)明:備份sql server---創(chuàng)建 備份數(shù)據(jù)的 device USE master EXEC sp_addumpdevice 'disk', 'testBack', 'c:mssql7backupMyNwind_1.dat'---開(kāi)始 備份

BACKUP DATABASE pubs TO testBack

4、說(shuō)明:創(chuàng)建新表

create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..)根據(jù)已有的表創(chuàng)建新表:

A:create table tab_new like tab_old(使用舊表創(chuàng)建新表)

B:create table tab_new as select col1,col2? from tab_old definition only

5、說(shuō)明:刪除新表 drop table tabname

6、說(shuō)明:增加一個(gè)列

Alter table tabname add column col type

注:列增加后將不能刪除。DB2中列加上后數(shù)據(jù)類(lèi)型也不能改變,唯一能改變的是增加varchar類(lèi)型的長(zhǎng)度。

7、說(shuō)明:添加主鍵: Alter table tabname add primary key(col)說(shuō)明:刪除主鍵: Alter table tabname drop primary key(col)

8、說(shuō)明:創(chuàng)建索引:create [unique] index idxname on tabname(col?.)刪除索引:drop index idxname

注:索引是不可更改的,想更改必須刪除重新建。

9、說(shuō)明:創(chuàng)建視圖:create view viewname as select statement 刪除視圖:drop view viewname

10、說(shuō)明:幾個(gè)簡(jiǎn)單的基本的sql語(yǔ)句 選擇:select * from table1 where 范圍

插入:insert into table1(field1,field2)values(value1,value2)刪除:delete from table1 where 范圍

更新:update table1 set field1=value1 where 范圍

查找:select * from table1 where field1 like ’%value1%’---like的語(yǔ)法很精妙,查資料!排序:select * from table1 order by field1,field2 [desc] 總數(shù):select count as totalcount from table1 求和:select sum(field1)as sumvalue from table1平均:select avg(field1)as avgvalue from table1 最大:select max(field1)as maxvalue from table1 最小:select min(field1)as minvalue from table1

11、說(shuō)明:幾個(gè)高級(jí)查詢(xún)運(yùn)算詞 A: UNION 運(yùn)算符

UNION 運(yùn)算符通過(guò)組合其他兩個(gè)結(jié)果表(例如 TABLE1 和 TABLE2)并消去表中任何重復(fù)行而派生出一個(gè)結(jié)果表。當(dāng) ALL 隨 UNION 一起使用時(shí)(即 UNION ALL),不消除重復(fù)行。兩種情況下,派生表的每一行不是來(lái)自 TABLE1 就是來(lái)自 TABLE2。B: EXCEPT 運(yùn)算符

EXCEPT 運(yùn)算符通過(guò)包括所有在 TABLE1 中但不在 TABLE2 中的行并消除所有重復(fù)行而派生出一個(gè)結(jié)果表。當(dāng) ALL 隨 EXCEPT 一起使用時(shí)(EXCEPT ALL),不消除重復(fù)行。

C: INTERSECT 運(yùn)算符

INTERSECT 運(yùn)算符通過(guò)只包括 TABLE1 和 TABLE2 中都有的行并消除所有重復(fù)行而派生出一個(gè)結(jié)果表。當(dāng) ALL 隨 INTERSECT 一起使用時(shí)(INTERSECT ALL),不消除重復(fù)行。注:使用運(yùn)算詞的幾個(gè)查詢(xún)結(jié)果行必須是一致的。

12、說(shuō)明:使用外連接

A、left(outer)join:

左外連接(左連接):結(jié)果集幾包括連接表的匹配行,也包括左連接表的所有行。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 B:right(outer)join:

右外連接(右連接):結(jié)果集既包括連接表的匹配連接行,也包括右連接表的所有行。C:full/cross(outer)join:

全外連接:不僅包括符號(hào)連接表的匹配行,還包括兩個(gè)連接表中的所有記錄。

12、分組:Group by: 一張表,一旦分組 完成后,查詢(xún)后只能得到組相關(guān)的信息。

組相關(guān)的信息:(統(tǒng)計(jì)信息)count,sum,max,min,avg 分組的標(biāo)準(zhǔn))

在SQLServer中分組時(shí):不能以text,ntext,image類(lèi)型的字段作為分組依據(jù) 在selecte統(tǒng)計(jì)函數(shù)中的字段,不能和普通的字段放在一起;

13、對(duì)數(shù)據(jù)庫(kù)進(jìn)行操作:

分離數(shù)據(jù)庫(kù): sp_detach_db;附加數(shù)據(jù)庫(kù):sp_attach_db 后接表明,附加需要完整的路徑名 14.如何修改數(shù)據(jù)庫(kù)的名稱(chēng):

sp_renamedb 'old_name', 'new_name'

二、提升

1、說(shuō)明:復(fù)制表(只復(fù)制結(jié)構(gòu),源表名:a 新表名:b)(Access可用)法一:select * into b from a where 1<>1(僅用于SQlServer)法二:select top 0 * into b from a

2、說(shuō)明:拷貝表(拷貝數(shù)據(jù),源表名:a 目標(biāo)表名:b)(Access可用)insert into b(a, b, c)select d,e,f from b;

3、說(shuō)明:跨數(shù)據(jù)庫(kù)之間表的拷貝(具體數(shù)據(jù)使用絕對(duì)路徑)(Access可用)insert into b(a, b, c)select d,e,f from b in ‘具體數(shù)據(jù)庫(kù)’ where 條件 例子:..from b in '“&Server.MapPath(”.“)&”data.mdb“ &”' where..2

4、說(shuō)明:子查詢(xún)(表名1:a 表名2:b)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)

5、說(shuō)明:顯示文章、提交人和最后回復(fù)時(shí)間

select a.title,a.username,b.adddate from table a,(select max(adddate)adddate from table where table.title=a.title)b

6、說(shuō)明:外連接查詢(xún)(表名1:a 表名2:b)select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c

7、說(shuō)明:在線視圖查詢(xún)(表名1:a)select * from(SELECT a,b,c FROM a)T where t.a > 1;

8、說(shuō)明:between的用法,between限制查詢(xún)數(shù)據(jù)范圍時(shí)包括了邊界值,not between不包括 select * from table1 where time between time1 and time2 select a,b,c, from table1 where a not between 數(shù)值1 and 數(shù)值2

9、說(shuō)明:in 的使用方法

select * from table1 where a [not] in(‘值1’,’值2’,’值4’,’值6’)

10、說(shuō)明:兩張關(guān)聯(lián)表,刪除主表中已經(jīng)在副表中沒(méi)有的信息

delete from table1 where not exists(select * from table2 where table1.field1=table2.field1)

11、說(shuō)明:四表聯(lián)查問(wèn)題:

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.....12、說(shuō)明:日程安排提前五分鐘提醒

SQL: select * from 日程安排 where datediff('minute',f開(kāi)始時(shí)間,getdate())>5

13、說(shuō)明:一條sql 語(yǔ)句搞定數(shù)據(jù)庫(kù)分頁(yè)

select top 10 b.* from(select top 20 主鍵字段,排序字段 from 表名 order by 排序字段 desc)a,表名 b where b.主鍵字段 = a.主鍵字段 order by a.排序字段 具體實(shí)現(xiàn):

關(guān)于數(shù)據(jù)庫(kù)分頁(yè):

declare @start int,@end int @sql nvarchar(600)set @sql=’select top’+str(@end-@start+1)+’+from top’+str(@str-1)+’Rid from T where Rid>-1)’ exec sp_executesql @sql

注意:在top后不能直接跟一個(gè)變量,所以在實(shí)際應(yīng)用中只有這樣的進(jìn)行特殊的處理。Rid為一個(gè)標(biāo)識(shí)列,如果top后還有具體的字段,這樣做是非常有好處的。因?yàn)檫@樣可以避免 top的字段如果是邏輯索引的,查詢(xún)的結(jié)果后實(shí)際表中的不一致(邏輯索引中的數(shù)據(jù)有可能和數(shù)據(jù)表中的不一致,而查詢(xún)時(shí)如果處在索引則首先查詢(xún)索引)

T where rid not in(select

14、說(shuō)明:前10條記錄

select top 10 * form table1 where 范圍

15、說(shuō)明:選擇在每一組b值相同的數(shù)據(jù)中對(duì)應(yīng)的a最大的記錄的所有信息(類(lèi)似這樣的用法可以用于論壇每月排行榜,每月熱銷(xiāo)產(chǎn)品分析,按科目成績(jī)排名,等等.)select a,b,c from tablename ta where a=(select max(a)from tablename tb where tb.b=ta.b)

16、說(shuō)明:包括所有在 TableA 中但不在 TableB和TableC 中的行并消除所有重復(fù)行而派生出一個(gè)結(jié)果表

(select a from tableA)except(select a from tableB)except(select a from tableC)

17、說(shuō)明:隨機(jī)取出10條數(shù)據(jù)

select top 10 * from tablename order by newid()

18、說(shuō)明:隨機(jī)選擇記錄 select newid()

19、說(shuō)明:刪除重復(fù)記錄

1),delete from tablename where id not in(select max(id)from tablename group by col1,col2,...)2),select distinct * into temp from tablename delete from tablename

insert into tablename select * from temp 評(píng)價(jià): 這種操作牽連大量的數(shù)據(jù)的移動(dòng),這種做法不適合大容量但數(shù)據(jù)操作

3),例如:在一個(gè)外部表中導(dǎo)入數(shù)據(jù),由于某些原因第一次只導(dǎo)入了一部分,但很難判斷具體位置,這樣只有在下一次全部導(dǎo)入,這樣也就產(chǎn)生好多重復(fù)的字段,怎樣刪除重復(fù)字段 alter table tablename--添加一個(gè)自增列

add column_b int identity(1,1)delete from tablename where column_b not in(select max(column_b)from tablename group by column1,column2,...)alter table tablename drop column column_b

20、說(shuō)明:列出數(shù)據(jù)庫(kù)里所有的表名

select name from sysobjects where type='U' // U代表用戶(hù)

21、說(shuō)明:列出表里的所有的列名

select name from syscolumns where id=object_id('TableName')

22、說(shuō)明:列示type、vender、pcs字段,以type字段排列,case可以方便地實(shí)現(xiàn)多重選擇,類(lèi)似select 中的case。

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 顯示結(jié)果:

type vender pcs 電腦 A 1

電腦 A 1 光盤(pán) B 2 光盤(pán) A 2 手機(jī) B 3 手機(jī) C 3

23、說(shuō)明:初始化表table1 TRUNCATE TABLE table1

24、說(shuō)明:選擇從10到15的記錄

select top 5 * from(select top 15 * from table order by id asc)table_別名 order by id desc

三、技巧 1、1=1,1=2的使用,在SQL語(yǔ)句組合時(shí)用的較多

“where 1=1” 是表示選擇全部 “where 1=2”全部不選,如:

if @strWhere!='' begin set @strSQL = 'select count(*)as Total from [' + @tblName + '] where ' + @strWhere end else begin set @strSQL = 'select count(*)as Total from [' + @tblName + ']' end 我們可以直接寫(xiě)成 錯(cuò)誤!未找到目錄項(xiàng)。

set @strSQL = 'select count(*)as Total from [' + @tblName + '] where 1=1 安定 '+ @strWhere

2、收縮數(shù)據(jù)庫(kù)--重建索引 DBCC REINDEX DBCC INDEXDEFRAG--收縮數(shù)據(jù)和日志 DBCC SHRINKDB DBCC SHRINKFILE

3、壓縮數(shù)據(jù)庫(kù)

dbcc shrinkdatabase(dbname)

4、轉(zhuǎn)移數(shù)據(jù)庫(kù)給新用戶(hù)以已存在用戶(hù)權(quán)限

exec sp_change_users_login 'update_one','newname','oldname' go

5、檢查備份集

RESTORE VERIFYONLY from disk='E:dvbbs.bak'

6、修復(fù)數(shù)據(jù)庫(kù)

ALTER DATABASE [dvbbs] SET SINGLE_USER GO DBCC CHECKDB('dvbbs',repair_allow_data_loss)WITH TABLOCK GO ALTER DATABASE [dvbbs] SET MULTI_USER GO

7、日志清除 SET NOCOUNT ON DECLARE @LogicalFileName sysname, @MaxMinutes INT, @NewSize INT

USE tablename--要操作的數(shù)據(jù)庫(kù)名

SELECT @LogicalFileName = 'tablename_log',--日志文件名 @MaxMinutes = 10,--Limit on time allowed to wrap log.@NewSize = 1--你想設(shè)定的日志文件的大小(M)Setup / initialize DECLARE @OriginalSize int SELECT @OriginalSize = size FROM sysfiles WHERE name = @LogicalFileName SELECT 'Original Size of ' + db_name()+ ' LOG is ' + CONVERT(VARCHAR(30),@OriginalSize)+ ' 8K pages or ' + CONVERT(VARCHAR(30),(@OriginalSize*8/1024))+ 'MB' FROM sysfiles WHERE name = @LogicalFileName CREATE TABLE DummyTrans(DummyColumn char(8000)not null)

DECLARE @Counter INT, @StartTime DATETIME, @TruncLog VARCHAR(255)SELECT @StartTime = GETDATE(), @TruncLog = 'BACKUP LOG ' + db_name()+ ' WITH TRUNCATE_ONLY' DBCC SHRINKFILE(@LogicalFileName, @NewSize)EXEC(@TruncLog)--Wrap the log if necessary.WHILE @MaxMinutes > DATEDIFF(mi, @StartTime, GETDATE())--time has not expired

AND @OriginalSize =(SELECT size FROM sysfiles WHERE name = @LogicalFileName)AND(@OriginalSize * 8 /1024)> @NewSize BEGIN--Outer loop.SELECT @Counter = 0 WHILE((@Counter < @OriginalSize / 16)AND(@Counter < 50000))BEGIN--update INSERT DummyTrans VALUES('Fill Log')DELETE DummyTrans SELECT @Counter = @Counter + 1 END EXEC(@TruncLog)END SELECT 'Final Size of ' + db_name()+ ' LOG is ' + CONVERT(VARCHAR(30),size)+ ' 8K pages or ' + CONVERT(VARCHAR(30),(size*8/1024))+ 'MB' FROM sysfiles WHERE name = @LogicalFileName DROP TABLE DummyTrans SET NOCOUNT OFF

8、說(shuō)明:更改某個(gè)表

exec sp_changeobjectowner 'tablename','dbo'

9、存儲(chǔ)更改全部表

CREATE PROCEDURE dbo.User_ChangeObjectOwnerBatch @OldOwner as NVARCHAR(128), @NewOwner as NVARCHAR(128)AS DECLARE @Name as NVARCHAR(128)DECLARE @Owner as NVARCHAR(128)DECLARE @OwnerName as NVARCHAR(128)DECLARE curObject CURSOR FOR select 'Name' = name, 'Owner' = user_name(uid)from sysobjects where user_name(uid)=@OldOwner order by name OPEN curObject FETCH NEXT FROM curObject INTO @Name, @Owner WHILE(@@FETCH_STATUS=0)BEGIN if @Owner=@OldOwner begin set @OwnerName = @OldOwner + '.' + rtrim(@Name)

exec sp_changeobjectowner @OwnerName, @NewOwner end--select @name,@NewOwner,@OldOwner FETCH NEXT FROM curObject INTO @Name, @Owner END close curObject deallocate curObject GO

10、SQL SERVER中直接循環(huán)寫(xiě)入數(shù)據(jù) declare @i int set @i=1 while @i<30 begin insert into test(userid)values(@i)set @i=@i+1 end 案例:

有如下表,要求就裱中所有沒(méi)有及格的成績(jī),在每次增長(zhǎng)0.1的基礎(chǔ)上,使他們剛好及格:

Name score Zhangshan 80

Lishi 59 Wangwu 50

Songquan 69

while((select min(score)from tb_table)<60)begin update tb_table set score =score*1.01 where score<60

if(select min(score)from tb_table)>60 break else continue end

數(shù)據(jù)開(kāi)發(fā)-經(jīng)典

1.按姓氏筆畫(huà)排序:

Select * From TableName Order By CustomerName Collate Chinese_PRC_Stroke_ci_as //從少到多2.數(shù)據(jù)庫(kù)加密: select encrypt('原始密碼')

select pwdencrypt('原始密碼')select pwdcompare('原始密碼','加密后密碼')= 1--相同;否則不相同 encrypt('原始密碼')select pwdencrypt('原始密碼')select pwdcompare('原始密碼','加密后密碼')= 1--相同;否則不相同 3.取回表中字段: declare @list varchar(1000), @sql nvarchar(1000)select @list=@list+','+b.name from sysobjects a,syscolumns b where a.id=b.id and a.name='表A' set @sql='select '+right(@list,len(@list)-1)+' from 表A' exec(@sql)4.查看硬盤(pán)分區(qū): EXEC master..xp_fixeddrives 5.比較A,B表是否相等: if(select checksum_agg(binary_checksum(*))from A)=(select checksum_agg(binary_checksum(*))from B)print '相等' else print '不相等' 6.殺掉所有的事件探察器進(jìn)程: DECLARE hcforeach CURSOR GLOBAL FOR SELECT 'kill '+RTRIM(spid)FROM master.dbo.sysprocesses WHERE program_name IN('SQL profiler',N'SQL 事件探查器')EXEC sp_msforeach_worker '?' 7.記錄搜索: 開(kāi)頭到N條記錄

Select Top N * From 表

N到M條記錄(要有主索引ID)Select Top M-N * From 表 Where ID in(Select Top M ID From 表)Order by ID Desc---N到結(jié)尾記錄

Select Top N * From 表 Order by ID Desc 案例

例如1:一張表有一萬(wàn)多條記錄,表的第一個(gè)字段 RecID 是自增長(zhǎng)字段,寫(xiě)一個(gè)SQL語(yǔ)句,找出表的第31到第40個(gè)記錄。

select top 10 recid from A where recid not in(select top 30 recid from A)分析:如果這樣寫(xiě)會(huì)產(chǎn)生某些問(wèn)題,如果recid在表中存在邏輯索引。

select top 10 recid from A where??是從索引中查找,而后面的select top 30 recid from A則在數(shù)據(jù)表中查找,這樣由于索引中的順序有可能和數(shù)據(jù)表中的不一致,這樣就導(dǎo)致查詢(xún)到的不是本來(lái)的欲得到的數(shù)據(jù)。解決方案

1,用order by select top 30 recid from A order by ricid 如果該字段不是自增長(zhǎng),就會(huì)出現(xiàn)問(wèn)題 2,在那個(gè)子查詢(xún)中也加條件:select top 30 recid from A where recid>-1

例2:查詢(xún)表中的最后以條記錄,并不知道這個(gè)表共有多少數(shù)據(jù),以及表結(jié)構(gòu)。

set @s = 'select top 1 * from T

where pid not in(select top ' + str(@count-1)+ ' pid from T)' print @s

exec sp_executesql

@s 9:獲取當(dāng)前數(shù)據(jù)庫(kù)中的所有用戶(hù)表

select Name from sysobjects where xtype='u' and status>=0 10:獲取某一個(gè)表的所有字段

select name from syscolumns where id=object_id('表名')select name from syscolumns where id in(select id from sysobjects where type = 'u' and name = '表名')兩種方式的效果相同

11:查看與某一個(gè)表相關(guān)的視圖、存儲(chǔ)過(guò)程、函數(shù)

select a.* from sysobjects a, syscomments b where a.id = b.id and b.text like '%表名%' 12:查看當(dāng)前數(shù)據(jù)庫(kù)中所有存儲(chǔ)過(guò)程

select name as 存儲(chǔ)過(guò)程名稱(chēng) from sysobjects where xtype='P' 13:查詢(xún)用戶(hù)創(chuàng)建的所有數(shù)據(jù)庫(kù)

select * from master..sysdatabases D where sid not in(select sid from master..syslogins where name='sa')或者

select dbid, name AS DB_NAME from master..sysdatabases where sid <> 0x01 14:查詢(xún)某一個(gè)表的字段和數(shù)據(jù)類(lèi)型

select column_name,data_type from information_schema.columns where table_name = '表名' 15:不同服務(wù)器數(shù)據(jù)庫(kù)之間的數(shù)據(jù)操作--創(chuàng)建鏈接服務(wù)器

exec sp_addlinkedserver 'ITSV ', ' ', 'SQLOLEDB ', '遠(yuǎn)程服務(wù)器名或ip地址 ' exec sp_addlinkedsrvlogin 'ITSV ', 'false ',null, '用戶(hù)名 ', '密碼 '--查詢(xún)示例

select * from ITSV.數(shù)據(jù)庫(kù)名.dbo.表名--導(dǎo)入示例

select * into 表 from ITSV.數(shù)據(jù)庫(kù)名.dbo.表名--以后不再使用時(shí)刪除鏈接服務(wù)器

exec sp_dropserver 'ITSV ', 'droplogins '

--連接遠(yuǎn)程/局域網(wǎng)數(shù)據(jù)(openrowset/openquery/opendatasource)--

1、openrowset--查詢(xún)示例

select * from openrowset('SQLOLEDB ', 'sql服務(wù)器名 ';'用戶(hù)名 ';'密碼 ',數(shù)據(jù)庫(kù)名.dbo.表名)

--生成本地表

select * into 表 from openrowset('SQLOLEDB ', 'sql服務(wù)器名 ';'用戶(hù)名 ';'密碼 ',數(shù)據(jù)庫(kù)名.dbo.表名)

--把本地表導(dǎo)入遠(yuǎn)程表

insert openrowset('SQLOLEDB ', 'sql服務(wù)器名 ';'用戶(hù)名 ';'密碼 ',數(shù)據(jù)庫(kù)名.dbo.表名)select *from 本地表--更新本地表 update b set b.列A=a.列A from openrowset('SQLOLEDB ', 'sql服務(wù)器名 ';'用戶(hù)名 ';'密碼 ',數(shù)據(jù)庫(kù)名.dbo.表名)as a inner join 本地表 b on a.column1=b.column1--openquery用法需要?jiǎng)?chuàng)建一個(gè)連接--首先創(chuàng)建一個(gè)連接創(chuàng)建鏈接服務(wù)器

exec sp_addlinkedserver 'ITSV ', ' ', 'SQLOLEDB ', '遠(yuǎn)程服務(wù)器名或ip地址 '--查詢(xún)

select * FROM openquery(ITSV, 'SELECT * FROM 數(shù)據(jù)庫(kù).dbo.表名 ')--把本地表導(dǎo)入遠(yuǎn)程表

insert openquery(ITSV, 'SELECT * FROM 數(shù)據(jù)庫(kù).dbo.表名 ')select * from 本地表--更新本地表 update b set b.列B=a.列B FROM openquery(ITSV, 'SELECT * FROM 數(shù)據(jù)庫(kù).dbo.表名 ')as a inner join 本地表 b on a.列A=b.列A

--

3、opendatasource/openrowset SELECT * FROM opendatasource('SQLOLEDB ', 'Data Source=ip/ServerName;User ID=登陸名;Password=密碼 ').test.dbo.roy_ta--把本地表導(dǎo)入遠(yuǎn)程表

insert opendatasource('SQLOLEDB ', 'Data Source=ip/ServerName;User ID=登陸名;Password=密碼 ').數(shù)據(jù)庫(kù).dbo.表名 select * from 本地表

SQL Server基本函數(shù)

SQL Server基本函數(shù) 1.字符串函數(shù) 長(zhǎng)度與分析用

1,datalength(Char_expr)返回字符串包含字符數(shù),但不包含后面的空格

2,substring(expression,start,length)取子串,字符串的下標(biāo)是從“1”,start為起始位置,length為字符串長(zhǎng)度,實(shí)際應(yīng)用中以len(expression)取得其長(zhǎng)度

3,right(char_expr,int_expr)返回字符串右邊第int_expr個(gè)字符,還用left于之相反

4,isnull(check_expression , replacement_value)如果check_expression為空,則返回replacement_value的值,不為空,就返回check_expression字符操作類(lèi)

5,Sp_addtype 自定義數(shù)據(jù)類(lèi)型

例如:EXEC sp_addtype birthday, datetime, 'NULL' 6,set nocount {on|off} 使返回的結(jié)果中不包含有關(guān)受 Transact-SQL 語(yǔ)句影響的行數(shù)的信息。如果存儲(chǔ)過(guò)程中包含的一些語(yǔ)句并不返回許多實(shí)際的數(shù)據(jù),則該設(shè)置由于大量減少了網(wǎng)絡(luò)流量,因此可顯著提高性能。SET NOCOUNT 設(shè)置是在執(zhí)行或運(yùn)行時(shí)設(shè)置,而不是在分析時(shí)設(shè)置。

SET NOCOUNT 為 ON 時(shí),不返回計(jì)數(shù)(表示受 Transact-SQL 語(yǔ)句影響的行數(shù))。SET NOCOUNT 為 OFF 時(shí),返回計(jì)數(shù)

常識(shí)

在SQL查詢(xún)中:from后最多可以跟多少?gòu)埍砘蛞晥D:256 在SQL語(yǔ)句中出現(xiàn) Order by,查詢(xún)時(shí),先排序,后取

在SQL中,一個(gè)字段的最大容量是8000,而對(duì)于nvarchar(4000),由于nvarchar是Unicode碼。

SQLServer2000同步復(fù)制技術(shù)實(shí)現(xiàn)步驟

一、預(yù)備工作

1.發(fā)布服務(wù)器,訂閱服務(wù)器都創(chuàng)建一個(gè)同名的windows用戶(hù),并設(shè)置相同的密碼,做為發(fā)布快照文件夾的有效訪問(wèn)用戶(hù)--管理工具--計(jì)算機(jī)管理--用戶(hù)和組--右鍵用戶(hù)

--新建用戶(hù)

--建立一個(gè)隸屬于administrator組的登陸windows的用戶(hù)(SynUser)2.在發(fā)布服務(wù)器上,新建一個(gè)共享目錄,做為發(fā)布的快照文件的存放目錄,操作: 我的電腦--D: 新建一個(gè)目錄,名為: PUB--右鍵這個(gè)新建的目錄--屬性--共享

--選擇“共享該文件夾”--通過(guò)“權(quán)限”按紐來(lái)設(shè)置具體的用戶(hù)權(quán)限,保證第一步中創(chuàng)建的用戶(hù)(SynUser)具有對(duì)該文件夾的所有權(quán)限

--確定

3.設(shè)置SQL代理(SQLSERVERAGENT)服務(wù)的啟動(dòng)用戶(hù)(發(fā)布/訂閱服務(wù)器均做此設(shè)置)開(kāi)始--程序--管理工具--服務(wù)--右鍵SQLSERVERAGENT--屬性--登陸--選擇“此賬戶(hù)”--輸入或者選擇第一步中創(chuàng)建的windows登錄用戶(hù)名(SynUser)--“密碼”中輸入該用戶(hù)的密碼

4.設(shè)置SQL Server身份驗(yàn)證模式,解決連接時(shí)的權(quán)限問(wèn)題(發(fā)布/訂閱服務(wù)器均做此設(shè)置)企業(yè)管理器

--右鍵SQL實(shí)例--屬性

--安全性--身份驗(yàn)證

--選擇“SQL Server 和 Windows”

--確定

5.在發(fā)布服務(wù)器和訂閱服務(wù)器上互相注冊(cè) 企業(yè)管理器

--右鍵SQL Server組

--新建SQL Server注冊(cè)...--下一步--可用的服務(wù)器中,輸入你要注冊(cè)的遠(yuǎn)程服務(wù)器名--添加--下一步--連接使用,選擇第二個(gè)“SQL Server身份驗(yàn)證”--下一步--輸入用戶(hù)名和密碼(SynUser)

--下一步--選擇SQL Server組,也可以創(chuàng)建一個(gè)新組--下一步--完成

6.對(duì)于只能用IP,不能用計(jì)算機(jī)名的,為其注冊(cè)服務(wù)器別名(此步在實(shí)施中沒(méi)用到)

(在連接端配置,比如,在訂閱服務(wù)器上配置的話,服務(wù)器名稱(chēng)中輸入的是發(fā)布服務(wù)器的IP)開(kāi)始--程序--Microsoft SQL Server--客戶(hù)端網(wǎng)絡(luò)實(shí)用工具--別名--添加

--網(wǎng)絡(luò)庫(kù)選擇“tcp/ip”--服務(wù)器別名輸入SQL服務(wù)器名

--連接參數(shù)--服務(wù)器名稱(chēng)中輸入SQL服務(wù)器ip地址

--如果你修改了SQL的端口,取消選擇“動(dòng)態(tài)決定端口”,并輸入對(duì)應(yīng)的端口號(hào)

二、正式配置

1、配置發(fā)布服務(wù)器

打開(kāi)企業(yè)管理器,在發(fā)布服務(wù)器(B、C、D)上執(zhí)行以下步驟:(1)從[工具]下拉菜單的[復(fù)制]子菜單中選擇[配置發(fā)布、訂閱服務(wù)器和分發(fā)]出現(xiàn)配置發(fā)布和分發(fā)向?qū)?2)[下一步] 選擇分發(fā)服務(wù)器 可以選擇把發(fā)布服務(wù)器自己作為分發(fā)服務(wù)器或者其他sql的服務(wù)器(選擇自己)

(3)[下一步] 設(shè)置快照文件夾

采用默認(rèn)servernamePub(4)[下一步] 自定義配置

可以選擇:是,讓我設(shè)置分發(fā)數(shù)據(jù)庫(kù)屬性啟用發(fā)布服務(wù)器或設(shè)置發(fā)布設(shè)置 否,使用下列默認(rèn)設(shè)置(推薦)

(5)[下一步] 設(shè)置分發(fā)數(shù)據(jù)庫(kù)名稱(chēng)和位置 采用默認(rèn)值(6)[下一步] 啟用發(fā)布服務(wù)器 選擇作為發(fā)布的服務(wù)器(7)[下一步] 選擇需要發(fā)布的數(shù)據(jù)庫(kù)和發(fā)布類(lèi)型(8)[下一步] 選擇注冊(cè)訂閱服務(wù)器(9)[下一步] 完成配置

2、創(chuàng)建出版物

發(fā)布服務(wù)器B、C、D上

(1)從[工具]菜單的[復(fù)制]子菜單中選擇[創(chuàng)建和管理發(fā)布]命令(2)選擇要?jiǎng)?chuàng)建出版物的數(shù)據(jù)庫(kù),然后單擊[創(chuàng)建發(fā)布](3)在[創(chuàng)建發(fā)布向?qū)的提示對(duì)話框中單擊[下一步]系統(tǒng)就會(huì)彈出一個(gè)對(duì)話框。對(duì)話框上的內(nèi)容是復(fù)制的三個(gè)類(lèi)型。我們現(xiàn)在選第一個(gè)也就是默認(rèn)的快照發(fā)布(其他兩個(gè)大家可以去看看幫助)(4)單擊[下一步]系統(tǒng)要求指定可以訂閱該發(fā)布的數(shù)據(jù)庫(kù)服務(wù)器類(lèi)型, SQLSERVER允許在不同的數(shù)據(jù)庫(kù)如 orACLE或ACCESS之間進(jìn)行數(shù)據(jù)復(fù)制。但是在這里我們選擇運(yùn)行“SQL SERVER 2000”的數(shù)據(jù)庫(kù)服務(wù)器

(5)單擊[下一步]系統(tǒng)就彈出一個(gè)定義文章的對(duì)話框也就是選擇要出版的表 注意: 如果前面選擇了事務(wù)發(fā)布 則再這一步中只能選擇帶有主鍵的表(6)選擇發(fā)布名稱(chēng)和描述

(7)自定義發(fā)布屬性 向?qū)峁┑倪x擇:

是 我將自定義數(shù)據(jù)篩選,啟用匿名訂閱和或其他自定義屬性 否 根據(jù)指定方式創(chuàng)建發(fā)布(建議采用自定義的方式)(8)[下一步] 選擇篩選發(fā)布的方式

(9)[下一步] 可以選擇是否允許匿名訂閱

1)如果選擇署名訂閱,則需要在發(fā)布服務(wù)器上添加訂閱服務(wù)器

方法: [工具]->[復(fù)制]->[配置發(fā)布、訂閱服務(wù)器和分發(fā)的屬性]->[訂閱服務(wù)器] 中添加 否則在訂閱服務(wù)器上請(qǐng)求訂閱時(shí)會(huì)出現(xiàn)的提示:改發(fā)布不允許匿名訂閱 如果仍然需要匿名訂閱則用以下解決辦法

[企業(yè)管理器]->[復(fù)制]->[發(fā)布內(nèi)容]->[屬性]->[訂閱選項(xiàng)] 選擇允許匿名請(qǐng)求訂閱 2)如果選擇匿名訂閱,則配置訂閱服務(wù)器時(shí)不會(huì)出現(xiàn)以上提示(10)[下一步] 設(shè)置快照 代理程序調(diào)度(11)[下一步] 完成配置

當(dāng)完成出版物的創(chuàng)建后創(chuàng)建出版物的數(shù)據(jù)庫(kù)也就變成了一個(gè)共享數(shù)據(jù)庫(kù) 有數(shù)據(jù)

srv1.庫(kù)名..author有字段:id,name,phone, srv2.庫(kù)名..author有字段:id,name,telphone,adress

要求:

srv1.庫(kù)名..author增加記錄則srv1.庫(kù)名..author記錄增加

srv1.庫(kù)名..author的phone字段更新,則srv1.庫(kù)名..author對(duì)應(yīng)字段telphone更新--*/

--大致的處理步驟

--1.在 srv1 上創(chuàng)建連接服務(wù)器,以便在 srv1 中操作 srv2,實(shí)現(xiàn)同步

exec sp_addlinkedserver 'srv2','','SQLOLEDB','srv2的sql實(shí)例名或ip' exec sp_addlinkedsrvlogin 'srv2','false',null,'用戶(hù)名','密碼' go--2.在 srv1 和 srv2 這兩臺(tái)電腦中,啟動(dòng) msdtc(分布式事務(wù)處理服務(wù)),并且設(shè)置為自動(dòng)啟動(dòng)

。我的電腦--控制面板--管理工具--服務(wù)--右鍵 Distributed Transaction Coordinator--屬性--啟動(dòng)--并將啟動(dòng)類(lèi)型設(shè)置為自動(dòng)啟動(dòng) go

--然后創(chuàng)建一個(gè)作業(yè)定時(shí)調(diào)用上面的同步處理存儲(chǔ)過(guò)程就行了

企業(yè)管理器--管理

--SQL Server代理--右鍵作業(yè)--新建作業(yè)

--“常規(guī)”項(xiàng)中輸入作業(yè)名稱(chēng)--“步驟”項(xiàng)

--新建

--“步驟名”中輸入步驟名

--“類(lèi)型”中選擇“Transact-SQL 腳本(TSQL)”--“數(shù)據(jù)庫(kù)”選擇執(zhí)行命令的數(shù)據(jù)庫(kù)

--“命令”中輸入要執(zhí)行的語(yǔ)句: exec p_process--確定--“調(diào)度”項(xiàng)--新建調(diào)度

--“名稱(chēng)”中輸入調(diào)度名稱(chēng)

--“調(diào)度類(lèi)型”中選擇你的作業(yè)執(zhí)行安排--如果選擇“反復(fù)出現(xiàn)”--點(diǎn)“更改”來(lái)設(shè)置你的時(shí)間安排

然后將SQL Agent服務(wù)啟動(dòng),并設(shè)置為自動(dòng)啟動(dòng),否則你的作業(yè)不會(huì)被執(zhí)行

設(shè)置方法: 我的電腦--控制面板--管理工具--服務(wù)--右鍵 SQLSERVERAGENT--屬性--啟動(dòng)類(lèi)型--選擇“自動(dòng)啟動(dòng)”--確定.--3.實(shí)現(xiàn)同步處理的方法2,定時(shí)同步

--在srv1中創(chuàng)建如下的同步處理存儲(chǔ)過(guò)程 create proc p_process as--更新修改過(guò)的數(shù)據(jù)

update b set name=i.name,telphone=i.telphone from srv2.庫(kù)名.dbo.author b,author i where b.id=i.id and(b.name <> i.name or b.telphone <> i.telphone)

--插入新增的數(shù)據(jù)

insert srv2.庫(kù)名.dbo.author(id,name,telphone)select id,name,telphone from author i where not exists(select * from srv2.庫(kù)名.dbo.author where id=i.id)

--刪除已經(jīng)刪除的數(shù)據(jù)(如果需要的話)delete b from srv2.庫(kù)名.dbo.author b where not exists(select * from author where id=b.id)go

第三篇:經(jīng)典實(shí)用SQL語(yǔ)句總結(jié)

經(jīng)典實(shí)用SQL語(yǔ)句大全總結(jié)

[編輯語(yǔ)言]2015-05-26 19:56

本文導(dǎo)航

1、首頁(yè)2、11、說(shuō)明:四表聯(lián)查問(wèn)題:

本文是經(jīng)典實(shí)用SQL語(yǔ)句大全的介紹,下面是該介紹的詳細(xì)信息。下列語(yǔ)句部分是Mssql語(yǔ)句,不可以在access中使用。SQL分類(lèi):

DDL—數(shù)據(jù)定義語(yǔ)言(CREATE,ALTER,DROP,DECLARE)DML—數(shù)據(jù)操縱語(yǔ)言(SELECT,DELETE,UPDATE,INSERT)DCL—數(shù)據(jù)控制語(yǔ)言(GRANT,REVOKE,COMMIT,ROLLBACK)首先,簡(jiǎn)要介紹基礎(chǔ)語(yǔ)句:

1、說(shuō)明:創(chuàng)建數(shù)據(jù)庫(kù)

CREATE DATABASE database-name

2、說(shuō)明:刪除數(shù)據(jù)庫(kù) drop database dbname

3、說(shuō)明:備份sql server---創(chuàng)建 備份數(shù)據(jù)的 device USE master EXEC sp_addumpdevice 'disk', 'testBack', 'c:mssql7backupMyNwind_1.dat'---開(kāi)始 備份

BACKUP DATABASE pubs TO testBack

4、說(shuō)明:創(chuàng)建新表

create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..)根據(jù)已有的表創(chuàng)建新表:

A:create table tab_new like tab_old(使用舊表創(chuàng)建新表)B:create table tab_new as select col1,col2… from tab_old definition only

5、說(shuō)明:

刪除新表:drop table tabname

6、說(shuō)明:

增加一個(gè)列:Alter table tabname add column col type 注:列增加后將不能刪除。DB2中列加上后數(shù)據(jù)類(lèi)型也不能改變,唯一能改變的是增加varchar類(lèi)型的長(zhǎng)度。

7、說(shuō)明:

添加主鍵:Alter table tabname add primary key(col)說(shuō)明:

刪除主鍵:Alter table tabname drop primary key(col)

8、說(shuō)明:

創(chuàng)建索引:create [unique] index idxname on tabname(col….)刪除索引:drop index idxname 注:索引是不可更改的,想更改必須刪除重新建。

9、說(shuō)明: 創(chuàng)建視圖:create view viewname as select statement 刪除視圖:drop view viewname

10、說(shuō)明:幾個(gè)簡(jiǎn)單的基本的sql語(yǔ)句 選擇:select * from table1 where 范圍

插入:insert into table1(field1,field2)values(value1,value2)刪除:delete from table1 where 范圍

更新:update table1 set field1=value1 where 范圍

查找:select * from table1 where field1 like ’%value1%’---like的語(yǔ)法很精妙,查資料!排序:select * from table1 order by field1,field2 [desc] 總數(shù):select count * as totalcount from table1 求和:select sum(field1)as sumvalue from table1平均:select avg(field1)as avgvalue from table1 最大:select max(field1)as maxvalue from table1 最小:select min(field1)as minvalue from table1

11、說(shuō)明:幾個(gè)高級(jí)查詢(xún)運(yùn)算詞 A: UNION 運(yùn)算符

UNION 運(yùn)算符通過(guò)組合其他兩個(gè)結(jié)果表(例如 TABLE1 和 TABLE2)并消去表中任何重復(fù)行而派生出一個(gè)結(jié)果表。當(dāng) ALL 隨 UNION 一起使用時(shí)(即 UNION ALL),不消除重復(fù)行。兩種情況下,派生表的每一行不是來(lái)自 TABLE1 就是來(lái)自 TABLE2。

B: EXCEPT 運(yùn)算符 EXCEPT 運(yùn)算符通過(guò)包括所有在 TABLE1 中但不在 TABLE2 中的行并消除所有重復(fù)行而派生出一個(gè)結(jié)果表。當(dāng) ALL 隨 EXCEPT 一起使用時(shí)(EXCEPT ALL),不消除重復(fù)行。

C: INTERSECT 運(yùn)算符

INTERSECT 運(yùn)算符通過(guò)只包括 TABLE1 和 TABLE2 中都有的行并消除所有重復(fù)行而派生出一個(gè)結(jié)果表。當(dāng) ALL 隨 INTERSECT 一起使用時(shí)(INTERSECT ALL),不消除重復(fù)行。

注:使用運(yùn)算詞的幾個(gè)查詢(xún)結(jié)果行必須是一致的。

12、說(shuō)明:使用外連接 A、left outer join:

左外連接(左連接):結(jié)果集幾包括連接表的匹配行,也包括左連接表的所有行。

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 B:right outer join: 右外連接(右連接):結(jié)果集既包括連接表的匹配連接行,也包括右連接表的所有行。

C:full outer join:

全外連接:不僅包括符號(hào)連接表的匹配行,還包括兩個(gè)連接表中的所有記錄。其次,大家來(lái)看一些不錯(cuò)的sql語(yǔ)句

1、說(shuō)明:復(fù)制表(只復(fù)制結(jié)構(gòu),源表名:a 新表名:b)(Access可用)法一:select * into b from a where 1<>1 法二:select top 0 * into b from a

2、說(shuō)明:拷貝表(拷貝數(shù)據(jù),源表名:a 目標(biāo)表名:b)(Access可用)insert into b(a, b, c)select d,e,f from b;

3、說(shuō)明:跨數(shù)據(jù)庫(kù)之間表的拷貝(具體數(shù)據(jù)使用絕對(duì)路徑)(Access可用)insert into b(a, b, c)select d,e,f from b in ‘具體數(shù)據(jù)庫(kù)’ where 條件 例子:..from b in '“&Server.MapPath(”.“)&”data.mdb“ &”' where..4、說(shuō)明:子查詢(xún)(表名1:a 表名2:b)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)

5、說(shuō)明:顯示文章、提交人和最后回復(fù)時(shí)間

select a.title,a.username,b.adddate from table a,(select max(adddate)adddate from table where table.title=a.title)b

6、說(shuō)明:外連接查詢(xún)(表名1:a 表名2:b)select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c

7、說(shuō)明:在線視圖查詢(xún)(表名1:a)select * from(SELECT a,b,c FROM a)T where t.a > 1;

8、說(shuō)明:between的用法,between限制查詢(xún)數(shù)據(jù)范圍時(shí)包括了邊界值,not between不包括

select * from table1 where time between time1 and time2 select a,b,c, from table1 where a not between 數(shù)值1 and 數(shù)值2

9、說(shuō)明:in 的使用方法

select * from table1 where a [not] in(‘值1’,’值2’,’值4’,’值6’)

10、說(shuō)明:兩張關(guān)聯(lián)表,刪除主表中已經(jīng)在副表中沒(méi)有的信息 delete from table1 where not exists(select * from table2 where table1.field1=table2.field1)

11、說(shuō)明:四表聯(lián)查問(wèn)題:

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.....12、說(shuō)明:日程安排提前五分鐘提醒

SQL: select * from 日程安排 where datediff('minute',f開(kāi)始時(shí)間,getdate())>5

13、說(shuō)明:一條sql 語(yǔ)句搞定數(shù)據(jù)庫(kù)分頁(yè)

select top 10 b.* from(select top 20 主鍵字段,排序字段 from 表名 order by 排序字段 desc)a,表名 b where b.主鍵字段 = a.主鍵字段 order by a.排序字段

14、說(shuō)明:前10條記錄

select top 10 * form table1 where 范圍

15、說(shuō)明:選擇在每一組b值相同的數(shù)據(jù)中對(duì)應(yīng)的a最大的記錄的所有信息(類(lèi)似這樣的用法可以用于論壇每月排行榜,每月熱銷(xiāo)產(chǎn)品分析,按科目成績(jī)排名,等等.)select a,b,c from tablename ta where a=(select max(a)from tablename tb where tb.b=ta.b)

16、說(shuō)明:包括所有在 TableA 中但不在 TableB和TableC 中的行并消除所有重復(fù)行而派生出一個(gè)結(jié)果表(select a from tableA)except(select a from tableB)except(select a from tableC)

17、說(shuō)明:隨機(jī)取出10條數(shù)據(jù)

select top 10 * from tablename order by newid()

18、說(shuō)明:隨機(jī)選擇記錄 select newid()

19、說(shuō)明:刪除重復(fù)記錄

Delete from tablename where id not in(select max(id)from tablename group by col1,col2,...)20、說(shuō)明:列出數(shù)據(jù)庫(kù)里所有的表名

select name from sysobjects where type='U'

21、說(shuō)明:列出表里的所有的

select name from syscolumns where id=object_id('TableName')

22、說(shuō)明:列示type、vender、pcs字段,以type字段排列,case可以方便地實(shí)現(xiàn)多重選擇,類(lèi)似select 中的case。

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 顯示結(jié)果: type vender pcs 電腦 A 1 電腦 A 1 光盤(pán) B 2 光盤(pán) A 2 手機(jī) B 3 手機(jī) C 3

23、說(shuō)明:初始化表table1 TRUNCATE TABLE table1

24、說(shuō)明:選擇從10到15的記錄

select top 5 * from(select top 15 * from table order by id asc)table_別名 order by id desc 隨機(jī)選擇數(shù)據(jù)庫(kù)記錄的方法(使用Randomize函數(shù),通過(guò)SQL語(yǔ)句實(shí)現(xiàn))對(duì)存儲(chǔ)在數(shù)據(jù)庫(kù)中的數(shù)據(jù)來(lái)說(shuō),隨機(jī)數(shù)特性能給出上面的效果,但它們可能太慢了些。你不能要求ASP“找個(gè)隨機(jī)數(shù)”然后打印出來(lái)。實(shí)際上常見(jiàn)的解決方案是建立如下所示的循環(huán):

Randomize RNumber = Int(Rnd*499)+1 While Not objRec.EOF If objRec(“ID”)= RNumber THEN...這里是執(zhí)行腳本...end if objRec.MoveNext Wend 這很容易理解。首先,你取出1到500范圍之內(nèi)的一個(gè)隨機(jī)數(shù)(假設(shè)500就是數(shù)據(jù)庫(kù)內(nèi)記錄的總數(shù))。然后,你遍歷每一記錄來(lái)測(cè)試ID 的值、檢查其是否匹配RNumber。滿(mǎn)足條件的話就執(zhí)行由THEN 關(guān)鍵字開(kāi)始的那一塊代碼。假如你的RNumber 等于495,那么要循環(huán)一遍數(shù)據(jù)庫(kù)花的時(shí)間可就長(zhǎng)了。雖然500這個(gè)數(shù)字看起來(lái)大了些,但相比更為穩(wěn)固的企業(yè)解決方案這還是個(gè)小型數(shù)據(jù)庫(kù)了,后者通常在一個(gè)數(shù)據(jù)庫(kù)內(nèi)就包含了成千上萬(wàn)條記錄。這時(shí)候不就死定了? 采用SQL,你就可以很快地找出準(zhǔn)確的記錄并且打開(kāi)一個(gè)只包含該記錄的 recordset,如下所示:

Randomize RNumber = Int(Rnd*499)+ 1 SQL = “SELECT * FROM Customers WHERE ID = ” & RNumber set objRec = ObjConn.Execute(SQL)Response.WriteRNumber & “ = ” & objRec(“ID”)& “ ” & objRec(“c_email”)不必寫(xiě)出RNumber 和ID,你只需要檢查匹配情況即可。只要你對(duì)以上代碼的工作滿(mǎn)意,你自可按需操作“隨機(jī)”記錄。Recordset沒(méi)有包含其他內(nèi)容,因此你很快就能找到你需要的記錄這樣就大大降低了處理時(shí)間。

再談隨機(jī)數(shù)

現(xiàn)在你下定決心要榨干Random 函數(shù)的最后一滴油,那么你可能會(huì)一次取出多條隨機(jī)記錄或者想采用一定隨機(jī)范圍內(nèi)的記錄。把上面的標(biāo)準(zhǔn)Random 示例擴(kuò)展一下就可以用SQL應(yīng)對(duì)上面兩種情況了。為了取出幾條隨機(jī)選擇的記錄并存放在同一recordset內(nèi),你可以存儲(chǔ)三個(gè)隨機(jī)數(shù),然后查詢(xún)數(shù)據(jù)庫(kù)獲得匹配這些數(shù)字的記錄:

SQL = “SELECT * FROM Customers WHERE ID = ” & RNumber & “ OR ID = ” & RNumber2 & “ OR ID = ” & RNumber3 假如你想選出10條記錄(也許是每次頁(yè)面裝載時(shí)的10條鏈接的列表),你可以用BETWEEN 或者數(shù)學(xué)等式選出第一條記錄和適當(dāng)數(shù)量的遞增記錄。這一操作可以通過(guò)好幾種方式來(lái)完成,但是 SELECT 語(yǔ)句只顯示一種可能(這里的ID 是自動(dòng)生成的號(hào)碼):

SQL = “SELECT * FROM Customers WHERE ID BETWEEN ” & RNumber & “ AND ” & RNumber & “+ 9” 注意:以上代碼的執(zhí)行目的不是檢查數(shù)據(jù)庫(kù)內(nèi)是否有9條并發(fā)記錄。隨機(jī)讀取若干條記錄,測(cè)試過(guò)

Access語(yǔ)法:SELECT top 10 * From 表名 ORDER BY Rnd(id)Sql server:select top n * from 表名 order by newid()mysql select * From 表名 Order By rand()Limit n Access左連接語(yǔ)法(最近開(kāi)發(fā)要用左連接,Access幫助什么都沒(méi)有,網(wǎng)上沒(méi)有Access的SQL說(shuō)明,只有自己測(cè)試, 現(xiàn)在記下以備后查)語(yǔ)法 select table1.fd1,table1,fd2,table2.fd2 From table1 left join table2 on table1.fd1,table2.fd1 where...使用SQL語(yǔ)句 用...代替過(guò)長(zhǎng)的字符串顯示 語(yǔ)法: SQL數(shù)據(jù)庫(kù):select case when len(field)>10 then left(field,10)+'...' else field end as news_name,news_id from tablename Access數(shù)據(jù)庫(kù):SELECT iif(len(field)>2,left(field,2)+'...',field)FROM tablename;Conn.Execute說(shuō)明 Execute方法

該方法用于執(zhí)行SQL語(yǔ)句。根據(jù)SQL語(yǔ)句執(zhí)行后是否返回記錄集,該方法的使用格式分為以下兩種:

1.執(zhí)行SQL查詢(xún)語(yǔ)句時(shí),將返回查詢(xún)得到的記錄集。用法為: Set 對(duì)象變量名=連接對(duì)象.Execute(“SQL 查詢(xún)語(yǔ)言”)Execute方法調(diào)用后,會(huì)自動(dòng)創(chuàng)建記錄集對(duì)象,并將查詢(xún)結(jié)果存儲(chǔ)在該記錄對(duì)象中,通過(guò)Set方法,將記錄集賦給指定的對(duì)象保存,以后對(duì)象變量就代表了該記錄集對(duì)象。

2.執(zhí)行SQL的操作性語(yǔ)言時(shí),沒(méi)有記錄集的返回。此時(shí)用法為: 連接對(duì)象.Execute “SQL 操作性語(yǔ)句” [, RecordAffected][, Option] ·RecordAffected 為可選項(xiàng),此出可放置一個(gè)變量,SQL語(yǔ)句執(zhí)行后,所生效的記錄數(shù)會(huì)自動(dòng)保存到該變量中。通過(guò)訪問(wèn)該變量,就可知道SQL語(yǔ)句隊(duì)多少條記錄進(jìn)行了操作。

·Option 可選項(xiàng),該參數(shù)的取值通常為adCMDText,它用于告訴ADO,應(yīng)該將Execute方法之后的第一個(gè)字符解釋為命令文本。通過(guò)指定該參數(shù),可使執(zhí)行更高效。

·BeginTrans、RollbackTrans、CommitTrans方法 這三個(gè)方法是連接對(duì)象提供的用于事務(wù)處理的方法。BeginTrans用于開(kāi)始一個(gè)事物;RollbackTrans用于回滾事務(wù);CommitTrans用于提交所有的事務(wù)處理結(jié)果,即確認(rèn)事務(wù)的處理。

事務(wù)處理可以將一組操作視為一個(gè)整體,只有全部語(yǔ)句都成功執(zhí)行后,事務(wù)處理才算成功;若其中有一個(gè)語(yǔ)句執(zhí)行失敗,則整個(gè)處理就算失敗,并恢復(fù)到處里前的狀態(tài)。

BeginTrans和CommitTrans用于標(biāo)記事務(wù)的開(kāi)始和結(jié)束,在這兩個(gè)之間的語(yǔ)句,就是作為事務(wù)處理的語(yǔ)句。判斷事務(wù)處理是否成功,可通過(guò)連接對(duì)象的Error集合來(lái)實(shí)現(xiàn),若Error集合的成員個(gè)數(shù)不為0,則說(shuō)明有錯(cuò)誤發(fā)生,事務(wù)處理失敗。Error集合中的每一個(gè)Error對(duì)象,代表一個(gè)錯(cuò)誤信息。

SQL語(yǔ)句大全精要 2006/10/26 13:46 DELETE 語(yǔ)句

DELETE語(yǔ)句:用于創(chuàng)建一個(gè)刪除查詢(xún),可從列在 FROM 子句之中的一個(gè)或多個(gè)表中刪除記錄,且該子句滿(mǎn)足 WHERE 子句中的條件,可以使用DELETE刪除多個(gè)記錄。

語(yǔ)法:DELETE [table.*] FROM table WHERE criteria 語(yǔ)法:DELETE * FROM table WHERE criteria='查詢(xún)的字' 說(shuō)明:table參數(shù)用于指定從其中刪除記錄的表的名稱(chēng)。

criteria參數(shù)為一個(gè)表達(dá)式,用于指定哪些記錄應(yīng)該被刪除的表達(dá)式。可以使用 Execute 方法與一個(gè) DROP 語(yǔ)句從數(shù)據(jù)庫(kù)中放棄整個(gè)表。不過(guò),若用這種方法刪除表,將會(huì)失去表的結(jié)構(gòu)。不同的是當(dāng)使用 DELETE,只有數(shù)據(jù)會(huì)被刪除;表的結(jié)構(gòu)以及表的所有屬性仍然保留,例如字段屬性及索引。

以上就是精品學(xué)習(xí)網(wǎng)提供的關(guān)于經(jīng)典實(shí)用SQL語(yǔ)句大全的內(nèi)容,希望對(duì)大家有所幫助。

第四篇:SQL語(yǔ)句總結(jié)

SQL語(yǔ)句總結(jié)

一、插入記錄

1. 插入固定的數(shù)值

語(yǔ)法:

INSERT[INTO]表名[(字段列表)]VALUES(值列表)

示例1:

Insert into Students values('Mary’,24,’mary@163.com’)

若沒(méi)有指定給Student表的哪些字段插入數(shù)據(jù):<情況一>表示給該表的所有字段插入數(shù)據(jù),根據(jù)數(shù)據(jù)的個(gè)數(shù),可以得知Students表中一共有3個(gè)字段<情況二>表中有4個(gè)字段,其中一個(gè)字段是標(biāo)識(shí)列。

示例2:

Insert into Students(Sname,Sage)values(‘Mary’,24)

指定給表中的Sname,Sage兩個(gè)字段插入數(shù)據(jù)。注意事項(xiàng):

1)該命令運(yùn)行一次向表中插入1條記錄。無(wú)法實(shí)現(xiàn)向已存在的某記錄中插入一個(gè)數(shù)據(jù)

2)如果不指定給哪些字段插入數(shù)值,則應(yīng)注意值列表的值個(gè)數(shù)

3)插入數(shù)據(jù)時(shí),注意值的數(shù)據(jù)類(lèi)型要與對(duì)應(yīng)的字段數(shù)據(jù)類(lèi)型匹配

4)插入數(shù)據(jù)時(shí),如果沒(méi)有給值的字段必須保證允許其為空

5)插入數(shù)據(jù)時(shí),要注意字段中的一些約束

2. 插入的記錄集為一個(gè)查詢(xún)結(jié)果

語(yǔ)法:

INSERTINTO表名[(字段列表)]SELECT 字段列表 FROM表WHERE條件 示例1:

InsertintoTeacherselectSname,Sage,SemailfromStudent

從Student表中查詢(xún)?nèi)齻€(gè)字段的全部記錄,插入Teacher表,沒(méi)有指定Teacher表的具體字段,表示給Teacher表的全部字段插入數(shù)值

示例2:

InsertintoTeacherselectSname,Sage,SemailfromStudentwhereSage>25

從Student表中查詢(xún)?nèi)齻€(gè)字段的部分記錄,插入Teacher表

示例3:

InsertintoTeacher(tid,tname)selectSname , SagefromStudent 從Student表中查詢(xún)兩個(gè)字段的全部記錄,插入到Teacher表中的tid,tname字段 注意事項(xiàng):

查詢(xún)表的字段要和插入表的字段數(shù)據(jù)類(lèi)型一一對(duì)應(yīng)

3. 生成表查詢(xún)

語(yǔ)法:

SELECT字段列表INTO新表名FROM原表WHERE條件

示例1:

SelectSname,Sage,SemailintonewStudentfrom Studentwhere Sage<20 從Student表中查詢(xún)出年齡小于20歲的學(xué)生的記錄生成新表newStudent

共6頁(yè)當(dāng)前第1頁(yè)

示例2:

Select Sname,Sage,SemailintonewStudentfromStudentwhere 1=2

利用Student表的表結(jié)構(gòu)生成新表newStudent,newStudent表中記錄為空

注意事項(xiàng):

執(zhí)行該語(yǔ)句時(shí),確保數(shù)據(jù)庫(kù)中不存在into關(guān)鍵字后面的指定的表名

二、刪除記錄

1)刪除滿(mǎn)足條件的記錄

語(yǔ)法:

DELETEFROM表名WHERE條件

示例1:

DeletefromStudentwhereSage<20

從Student表中刪除年齡小于20歲的學(xué)生的記錄

示例2:

DeletefromStudent

沒(méi)有設(shè)置條件,刪除Student表的全部記錄

2)刪除表的全部記錄

語(yǔ)法:

TRUNCATETABLE表名

示例:

TruncatetableStudent

刪除表Student中的全部記錄,約束依然存在三、修改記錄

語(yǔ)法:

UPDATE表名SET字段=新值WHERE條件

示例1:

UpdateStudentsetSemail=’Email’+SemailwhereSemailisnotnull

把有email的學(xué)員的email地址變?yōu)樵鹊牡刂非凹由稀瓻mail’字符串

示例2:

UpdateStudentsetSage=Sage+1

把所有記錄的Sage變?yōu)樵鹊闹导?,例如過(guò)一年學(xué)生要長(zhǎng)一歲

四、查詢(xún)記錄

1. 基本查詢(xún)

語(yǔ)法:

SELECT字段列表FROM表

示例1:

SelectsName,sAge,sEmailfromStudents

從Students表中查詢(xún)3個(gè)字段的所有的記錄

示例2:

Select*fromStudents

從Students表中查詢(xún)所有字段的所有的記錄(字段列表位置寫(xiě)*代表查詢(xún)表中所有字段)

2. 帶WHERE子句的查詢(xún)

語(yǔ)法:

SELECT字段列表FROM表WHERE條件

示例1:

SelectSNamefromStudentswhereSage>23

查詢(xún)Students表中年齡大于23的學(xué)員的姓名

3. 應(yīng)用別名

語(yǔ)法1:

SELECT字段列表AS別名??

示例1:

SelectSNameas學(xué)員姓名,sAgeas學(xué)員年齡fromStudents

將查詢(xún)的兩個(gè)字段分別用中文別名顯示

語(yǔ)法2:

SELECT別名=字段??

示例2:

Select學(xué)員姓名=sName, 學(xué)員年齡=sAgefromStudents

注意事項(xiàng):

別名可以是英文,也可以是中文,別名可以用單引號(hào)引起,也可以不引

4. 使用常量(利用‘+’連接字段和常量)

示例:

SelectsName+’的年齡是’+convert(varchar(2),sAge)as 學(xué)員信息

from Students

從Students表中查詢(xún),將學(xué)員的姓名和年齡信息與一個(gè)常量連接起來(lái),顯示為一個(gè)字段,該字段以“學(xué)員信息”為別名

5. 限制返回的行數(shù)

語(yǔ)法1:

SELECTTOPN字段列表 FROM表

示例1:

Select top 3sName,sAgefromStudents

查詢(xún)Students表的前三條記錄

語(yǔ)法2:

SELECTTOPNPERCENT字段列表FROM表

示例2:

Selecttop30percentsName,sAge from Students

查詢(xún)Students表的前30%條記錄

6. 排序

語(yǔ)法:

SELECT字段列表FROM表WHERE條件ORDER BY字段ASC/DESC 示例1:

Select*fromStudentswhere sAge>20order by sAge

查詢(xún)年齡大于20歲的學(xué)員信息,并且按照年齡升序排序(若不指定升降序,默認(rèn)為升序)示例2:

Select*fromStudentsorder by sNamedesc

查詢(xún)所有學(xué)生的所有信息,并按照學(xué)生的姓名降序排序

7. 模糊查詢(xún)

1)Like:通常與通配符結(jié)合使用,適用于文本類(lèi)型的字段

示例1:

Select * from StudentswheresNamelike ‘張_’

查詢(xún)Students表中張姓的,兩個(gè)字名的學(xué)生信息

示例2:

Select * from StudentswheresNamelike ‘張%’

查詢(xún)Students表中張姓的學(xué)生的信息

示例3:

Select * from StudentswheresEmaillike ‘%@[a-z]%’

查詢(xún)Students表中,Semail字段‘@’后的第一個(gè)字符為小寫(xiě)英文字母的學(xué)生信息 示例4:

Select * from StudentswherestuNamelike ‘%@[^a-z]%’

查詢(xún)Students表中,Semail字段‘@’后的第一個(gè)字符不是小寫(xiě)英文字母的學(xué)生信息

2)Between ?and?:用于查詢(xún)條件為一個(gè)字段介于兩個(gè)值之間

示例:

Select * from Students where Sage between 20and25

查詢(xún)學(xué)員年齡在20到25之間的學(xué)員信息

3)In:用于查詢(xún)某個(gè)字段在值列表中出現(xiàn)作為條件

示例:

Select*fromStudentswhereScityin(‘大連’,’沈陽(yáng)’,’北京’)查詢(xún)學(xué)員的城市在大連,沈陽(yáng)或北京的學(xué)員信息,等價(jià)于如下功能:

Select * from Students where Scity=’大連’or Scity=’沈陽(yáng)’or Scity=’北京’

4)Isnull:用于查詢(xún)某個(gè)字段為空作為條件

示例:

Select * from Students where Semail is null

查詢(xún)學(xué)員的email為空的學(xué)員信息

Select * from Students where semail is not null

查詢(xún)學(xué)員的email不為空的學(xué)員信息

8. 聚合函數(shù)(所有函數(shù)自動(dòng)忽略空值)

1)Sum():統(tǒng)計(jì)某字段的和,用于數(shù)值型數(shù)據(jù)

示例:

Select sum(Sage)as 學(xué)員的年齡和 from Student

統(tǒng)計(jì)Students表中所有學(xué)員的年齡總和,顯示結(jié)果為一個(gè)字段一條記錄

2)Avg():統(tǒng)計(jì)某字段的平均值,用于數(shù)值型數(shù)據(jù)

示例:

Select avg(Sage)as 學(xué)員的平均年齡fromStudents

統(tǒng)計(jì)Students表中所有學(xué)員的年齡的平均值,顯示結(jié)果為一個(gè)字段一條記錄

3)Max():統(tǒng)計(jì)某字段的最大值,用于數(shù)值,文本,日期型

4)Min():統(tǒng)計(jì)某字段的最小值,用于數(shù)值,文本,日期型

示例:

Select max(Sage)as 最大年齡 , min(Sage)as 最小年齡from Students

查詢(xún)Students表中的學(xué)員的最大年齡和最小年齡,顯示結(jié)果為兩個(gè)字段一條記錄

5)Count():統(tǒng)計(jì)某字段的記錄數(shù)或者表的記錄數(shù)

示例1:

Select count(Semail)as email的數(shù)量 fromStudents

查詢(xún)Students表中,有email的學(xué)員的數(shù)量。Count(字段)代表統(tǒng)計(jì)字段的記錄數(shù) 示例2:

Select count(*)as學(xué)員的數(shù)量fromStudents

查詢(xún)Students表中的記錄數(shù),count(*)代表統(tǒng)計(jì)表的記錄數(shù)

9. 分組與聚合函數(shù)

語(yǔ)法:

SELECT字段1,聚合函數(shù)(字段)AS別名

FROM表

WHERE條件1

GROUP BY字段1

HAVING條件2

ORDER BY字段

注意事項(xiàng): 1)此語(yǔ)法格式用于對(duì)表中按照某個(gè)字段分類(lèi)之后,對(duì)每類(lèi)中的某個(gè)數(shù)據(jù)進(jìn)行統(tǒng)計(jì)

2)分組的字段應(yīng)該是包含大量重復(fù)數(shù)據(jù)的字段

3)只有出現(xiàn)的group by后的字段,才可以獨(dú)立出現(xiàn)在select后

4)Where條件用于在分組之前進(jìn)行對(duì)記錄的過(guò)濾

5)Having條件用于對(duì)分組之后的記錄集進(jìn)行條件過(guò)濾

6)Orderby總是出現(xiàn)在最后,對(duì)最終的結(jié)果集進(jìn)行排序

示例1:

SelectSsex,avg(Sage)as平均年齡fromStudent

Group by Ssex

統(tǒng)計(jì)Student表中男生和女生的平均年齡。按照性別分組,分為男生和女生兩組,統(tǒng)計(jì)每組中年齡的平均值

示例2:

SelectSsex,avg(Sage)as平均年齡fromStudents

WhereSemail is not null

Group by Ssex

統(tǒng)計(jì)具有email的學(xué)員中,男生和女生的平均年齡。先根據(jù)Smail字段進(jìn)行條件過(guò)濾,過(guò)濾掉沒(méi)有email的學(xué)員,對(duì)有email的學(xué)員分為男生和女孩兩組,統(tǒng)計(jì)每組中年齡的平均值

示例3:

SelectSdate,count(*)as人數(shù)

FromStudents

Group by Sdate

Havingcount(*)>10

統(tǒng)計(jì)每天報(bào)名的人數(shù),并顯示出報(bào)名人數(shù)多于10人的記錄。先按照?qǐng)?bào)名的日期進(jìn)行分組,統(tǒng)計(jì)出每天的報(bào)名人數(shù),再在分組之后的記錄集上進(jìn)行條件過(guò)濾,留下人數(shù)超過(guò)10人的記錄。

示例4:

SelectSdate,count(*)as人數(shù)

From Students

Where xueli=’大專(zhuān)’

Group by Sdate

Having by count(*)>10

查詢(xún)大專(zhuān)學(xué)歷的學(xué)員中,每天報(bào)名的人數(shù),并顯示多于10人的記錄。先按照學(xué)歷為大專(zhuān)的條件進(jìn)行過(guò)濾,把是大專(zhuān)的學(xué)員按照?qǐng)?bào)名日期進(jìn)行分組,統(tǒng)計(jì)每組的報(bào)名人數(shù),再把分組之后的記錄集進(jìn)行再次過(guò)濾,顯示出報(bào)名人數(shù)多于10人的信息

10. 多表查詢(xún) 注意事項(xiàng):

1)能夠進(jìn)行多表聯(lián)接查詢(xún)的表中必須包含有公共字段,兩個(gè)表的公共字段不要求字段名相同,但數(shù)據(jù)類(lèi)型必須相同,功能相同,且兩個(gè)字段中要包含相同記錄

2)最常用的聯(lián)接為內(nèi)聯(lián)接

1)內(nèi)聯(lián)接

SELECT字段列表

FROM表1INNERJOIN表2

ON表1.公共字段=表2.公共字段

返回兩個(gè)表基于公共字段有相同記錄的匹配結(jié)果

SELECT字段列表

FROM表1INNERJOIN表2

ON表1.公共字段<>表2.公共字段

返回兩個(gè)表的交叉聯(lián)接的結(jié)果與相等條件的內(nèi)聯(lián)的差集

2)外聯(lián)接

(1)左外聯(lián)接

SELECT字段列表

FROM左表LEFTJOIN右表

ON左表.公共字段=右表.公共字段

返回內(nèi)聯(lián)的結(jié)果加上左表的剩余記錄

(2)右外聯(lián)接

SELECT字段列表

FROM左表RIGHTJOIN右表

ON左表.公共字段=表2.公共字段

返回內(nèi)聯(lián)的結(jié)果加上右表的剩余記錄

(3)完整外聯(lián)接

SELECT字段列表

FROM表1FULLJOIN表2

ON表1.公共字段=表2.公共字段

返回內(nèi)聯(lián)的結(jié)果加上左表的剩余和右表的剩余

3)交叉聯(lián)接

SELECT字段列表

FROM表1CROSSJOIN表2

返回結(jié)果集的數(shù)目為表1的記錄數(shù)*表2的記錄數(shù),表1中的每一條記錄分別和表2中的每條記錄進(jìn)行匹配

4)自聯(lián)接

SELECT字段列表

FROM表1AS別名1INNERJOIN表1AS別名2

ON別名1.公共字段=別名2.公共字段

第五篇:sql常用語(yǔ)句

//創(chuàng)建臨時(shí)表空間

create temporary tablespace test_temp

tempfile 'E:oracleproduct10.2.0oradatatestservertest_temp01.dbf'size 32m

autoextend on

next 32m maxsize 2048m

extent management local;

//創(chuàng)建數(shù)據(jù)表空間

create tablespace test_data

logging

datafile 'E:oracleproduct10.2.0oradatatestservertest_data01.dbf'size 32m

autoextend on

next 32m maxsize 2048m

extent management local;

//創(chuàng)建用戶(hù)并指定表空間

create user username identified by password

default tablespace test_data

temporary tablespace test_temp;

//給用戶(hù)授予權(quán)限

//一般用戶(hù)

grant connect,resource to username;

//系統(tǒng)權(quán)限

grant connect,dba,resource to username

//創(chuàng)建用戶(hù)

create user user01 identified by u01

//建表

create table test7272(id number(10),name varchar2(20),age number(4),joindate date default sysdate,primary key(id));

//存儲(chǔ)過(guò)程

//數(shù)據(jù)庫(kù)連接池

數(shù)據(jù)庫(kù)連接池負(fù)責(zé)分配、管理和釋放數(shù)據(jù)庫(kù)連接

//

//創(chuàng)建表空間

create tablespace thirdspace

datafile 'C:/Program Files/Oracle/thirdspace.dbf' size 10mautoextend on;

//創(chuàng)建用戶(hù)

create user binbin

identified by binbin

default tablespace firstspace

temporary tablespace temp;

//賦予權(quán)限

GRANT CONNECT, SYSDBA, RESOURCE to binbin

//null與""的區(qū)別

簡(jiǎn)單點(diǎn)說(shuō)null表示還沒(méi)new出對(duì)象,就是還沒(méi)開(kāi)辟空間

個(gè)對(duì)象裝的是空字符串。

//建視圖

create view viewname

as

sql

//建索引

create index indexname on tablename(columnname)

//在表中增加一列

alter table tablename add columnname columntype

//刪除一列

alter table tablename drop columnname

//刪除表格內(nèi)容,表格結(jié)構(gòu)不變

truncate table tableneme

//新增數(shù)據(jù)

insert into tablename()values()

//直接新增多條數(shù)據(jù)

insert into tablename()

selecte a,b,c

from tableabc

//更新數(shù)據(jù) new除了對(duì)象,但是這“”表示

update tablename set columnname=? where

//刪除數(shù)據(jù)

delete from tablename

where

//union語(yǔ)句

sql

union

sql

//case

case

when then

else

end

下載常用SQL語(yǔ)句 工作兩年總結(jié) 個(gè)個(gè)經(jīng)典 不斷更新word格式文檔
下載常用SQL語(yǔ)句 工作兩年總結(jié) 個(gè)個(gè)經(jīng)典 不斷更新.doc
將本文檔下載到自己電腦,方便修改和收藏,請(qǐng)勿使用迅雷等下載。
點(diǎn)此處下載文檔

文檔為doc格式


聲明:本文內(nèi)容由互聯(lián)網(wǎng)用戶(hù)自發(fā)貢獻(xiàn)自行上傳,本網(wǎng)站不擁有所有權(quán),未作人工編輯處理,也不承擔(dān)相關(guān)法律責(zé)任。如果您發(fā)現(xiàn)有涉嫌版權(quán)的內(nèi)容,歡迎發(fā)送郵件至:645879355@qq.com 進(jìn)行舉報(bào),并提供相關(guān)證據(jù),工作人員會(huì)在5個(gè)工作日內(nèi)聯(lián)系你,一經(jīng)查實(shí),本站將立刻刪除涉嫌侵權(quán)內(nèi)容。

相關(guān)范文推薦

    SQL語(yǔ)句大全

    SQL練習(xí)一、 設(shè)有如下的關(guān)系模式, 試用SQL語(yǔ)句完成以下操作: 學(xué)生(學(xué)號(hào),姓名,性別,年齡,所在系) 課程(課程號(hào),課程名,學(xué)分,學(xué)期,學(xué)時(shí)) 選課(學(xué)號(hào),課程號(hào),成績(jī)) 1. 求選修了課程號(hào)為“C2”......

    SQL語(yǔ)句

    SQL語(yǔ)句,用友的SQL2000,通過(guò)查詢(xún)管理器寫(xiě)的語(yǔ)句 1、查詢(xún) 2、修改 3、刪除 4、插入表名:users 包含字段:id,sname,sage 查詢(xún) select * from users查詢(xún)users表中所有數(shù)據(jù) select i......

    常用SQL語(yǔ)句

    一、創(chuàng)建數(shù)據(jù)庫(kù) create database 數(shù)據(jù)庫(kù)名 on( name='數(shù)據(jù)庫(kù)名_data', size='數(shù)據(jù)庫(kù)文件大小', maxsize='數(shù)據(jù)庫(kù)文件最大值', filegrowth=5%,//數(shù)據(jù)庫(kù)文件的增長(zhǎng)率 filename......

    sql語(yǔ)句

    簡(jiǎn)單基本的sql語(yǔ)句 幾個(gè)簡(jiǎn)單的基本的sql語(yǔ)句 選擇:select * from table1 where范圍 插入:insert into table1(field1,field2) values(value1,value2) 刪除:delete from table1......

    常用sql語(yǔ)句

    1、查看表空間的名稱(chēng)及大小 select t.tablespace_name, round(sum(bytes/(1024*1024)),0) ts_size from dba_tablespaces t, dba_data_files d where t.tablespace_name = d......

    SQL基礎(chǔ)語(yǔ)句總結(jié)

    一. 四種基本的SQL語(yǔ)句 1. 查詢(xún) select * from table 2. 更新 update table set field=value 3. 插入 insert [into] table (field) values(value) 4. 刪除 delete [from] t......

    50個(gè)經(jīng)典sql語(yǔ)句總結(jié)

    一個(gè)項(xiàng)目涉及到的50個(gè)Sql語(yǔ)句(整理版) --1.學(xué)生表 Student(S,Sname,Sage,Ssex) --S 學(xué)生編號(hào),Sname 學(xué)生姓名,Sage 出生年月,Ssex 學(xué)生性別 --2.課程表 Course(C,Cname,T)......

    SQL注射語(yǔ)句的經(jīng)典總結(jié)

    SQL注射語(yǔ)句的經(jīng)典總結(jié) SQL注射語(yǔ)句的經(jīng)典總結(jié) SQL注射語(yǔ)句1.判斷有無(wú)注入點(diǎn)' ; and 1=1 and 1=2 2.猜表一般的表的名稱(chēng)無(wú)非是admin adminuser user pass password 等.. a......

主站蜘蛛池模板: 国产一区二区三区四区五区vm| 人妻少妇被猛烈进入中文字幕| 国产精品久久久久久52avav| 国产va免费精品观看精品| 欧洲免费一区二区三区视频| 国产精品久久久久久成人影院| 国产熟妇久久777777| av无码岛国免费动作片| 手机无码人妻一区二区三区免费| 亚洲综合网站精品一区二区| 精品久久久久久成人av| 久久天天躁夜夜躁狠狠躁2022| 国产午夜福利亚洲第一| 精品无人区乱码1区2区3区在线| 美女久久| 精品无码乱码av| 精品无人码麻豆乱码1区2区| 成人亚洲精品777777| 亚洲欧美成人a∨观看| 热久久美女精品天天吊色| 欧亚激情偷乱人伦小说专区| 国产高清不卡免费视频| 十八岁以下禁止观看黄下载链接| 午夜精品久久久内射近拍高清| 久久99日韩国产精品久久99| 55夜色66夜色国产精品视频| 污污内射久久一区二区欧美日韩| 久久综合亚洲色1080p| 精品人妻午夜一区二区三区四区| 日本真人边吃奶边做爽动态图| 97精品国产久热在线观看| 国产亚洲一区二区手机在线观看| 久久成人免费精品网站| 日本护士xxxxhd少妇| 无遮挡h肉动漫在线观看| 中文字幕在线不卡一区二区| 亚洲成a∨人片在线观看不卡| 麻豆视传媒精品av在线| 日本乱码一区二区三区不卡| 亚洲日韩在线观看免费视频| 奇米影视888欧美在线观看|