SQL用法總結(jié)
--=======================checkspacesandcleandata====================================--checkalldbsspacesp_helpdb
--checkalltablesspace
createtable#test(namevarchar(50),rowsint,reservedvarchar(20),datavarchar(20),index_sizevarchar(20),unusedvarchar(20))
insertinto#test
execsp_MSforeachtable"execsp_spaceused"?""
select*from#testorderbycast(replace(reserved,"KB","")asint)desc
droptable#test
--cleanalltabledata/*
execsp_MSforeachtable"deletefrom?"execsp_MSforeachtable"truncatetable?"*/
--========================處理日志====================================--由于SQL201*對(duì)文件和日志管理進(jìn)行了優(yōu)化,所以以下語句在SQL201*中可以運(yùn)行但在SQL201*中已經(jīng)被取消:--SQL201*/*
BackupLogDNNamewithno_log
DumpTransactionDNNamewithno_log
DBCCSHRINKFILE(2)*/
--SQL201*
--在SQL201*中清除日志就必須在簡單模式下進(jìn)行,等清除動(dòng)作完畢再調(diào)回到完全模式.
ALTERDATABASEDNNameSETRECOVERYSIMPLE--WITHNO_WAIT簡單模式
DBCCSHRINKFILE("DNName_Log",EMPTYFILE,TRUNCATEONLY)--DBCCSHRINKFILE("DNName_Log",1,TRUNCATEONLY)
ALTERDATABASEDNNameSETRECOVERYFULL--WITHNO_WAIT還原為完全模式
--優(yōu)點(diǎn):此清除日志所運(yùn)行消耗的時(shí)間短,90GB的日志在分鐘左右即可清除完畢,做完之后做個(gè)完全備份在分鐘內(nèi)即可完成.
--缺點(diǎn):不過此動(dòng)作最好不要經(jīng)常使用,因?yàn)樗倪\(yùn)行會(huì)帶來系統(tǒng)碎片.普通狀態(tài)下LOG和DIFF的備份即可截?cái)嗳罩?
--此語句使用的恰當(dāng)環(huán)境:當(dāng)系統(tǒng)的日志文件異常增大或者備份LOG時(shí)間太長可能影響生產(chǎn)的情況下使用.
--========================Rankingwindow
functions====================================--runonAdventureWorks
--UsingtheOVERclausewithaggregatefunctionsSELECTSalesOrderID,ProductID,OrderQty
,SUM(OrderQty)OVER(PARTITIONBYSalesOrderID)AS"Total",AVG(OrderQty)OVER(PARTITIONBYSalesOrderID)AS"Avg"
,COUNT(OrderQty)OVER(PARTITIONBYSalesOrderID)AS"Count",MIN(OrderQty)OVER(PARTITIONBYSalesOrderID)AS"Min",MAX(OrderQty)OVER(PARTITIONBYSalesOrderID)AS"Max"
,CAST(1.*OrderQty/SUM(OrderQty)OVER(PARTITIONBYSalesOrderID)*100ASDECIMAL(5,2))AS"PercentbyProductID"FROMSales.SalesOrderDetail
WHERESalesOrderIDIN(43659,43664)
--UsingtheOVERclausewiththeROW_NUMBERfunctionSELECTc.FirstName,c.LastName
,ROW_NUMBER()OVER(partitionbyPostalCodeORDERBYSalesYTDDESC)AS"RowNumber"
,s.SalesYTD,a.PostalCodeFROMSales.SalesPersons
INNERJOINPerson.Contactc
ONs.SalesPersonID=c.ContactIDINNERJOINPerson.Addressa
ONa.AddressID=c.ContactIDWHERETerritoryIDISNOTNULLANDSalesYTD0
SELECTc.FirstName,c.LastName
,ROW_NUMBER()OVER(ORDERBYa.PostalCode)AS"RowNumber",RANK()OVER(ORDERBYa.PostalCode)AS"Rank"
,DENSE_RANK()OVER(ORDERBYa.PostalCode)AS"DenseRank",NTILE(4)OVER(ORDERBYa.PostalCode)AS"Quartile",s.SalesYTD,a.PostalCodeFROMSales.SalesPersons
INNERJOINPerson.Contactc
ONs.SalesPersonID=c.ContactIDINNERJOINPerson.Addressa
ONa.AddressID=c.ContactIDWHERETerritoryIDISNOTNULLANDSalesYTD0
--=======================CreatePartitionondatabase====================================
--1.AddfilegroupsandfilestodatabaseALTERDATABASETestADDfilegrouptestFg1
ALTERDATABASETestADDFILE(NAME=test1,FILENAME="C:\\ProgramFiles\\MicrosoftSQL
Server\\MSSQL10.MSSQLSERVER\\MSSQL\\DATA\\test1.ndf",SIZE=3MB,MAXSIZE=UNLIMITED,FILEGROWTH=1MB
)TOFILEGROUPtestFg
ALTERDATABASETestADDfilegrouptestFg2
ALTERDATABASETestADDFILE(NAME=test1,FILENAME="C:\\ProgramFiles\\MicrosoftSQL
Server\\MSSQL10.MSSQLSERVER\\MSSQL\\DATA\\test2.ndf",SIZE=3MB,MAXSIZE=UNLIMITED,FILEGROWTH=1MB
)TOFILEGROUPtestFg2GO
--2.createpartitionfunctionandschemeCREATEPARTITIONFUNCTIONmyRangePF1(int)
ASRANGERIGHTFORVALUES(201*0101,201*0101,201*0101);GO
CREATEPARTITIONSCHEMEmyRangePS1ASPARTITIONmyRangePF1
TO([PRIMARY],testFg1,testFg2,testFg3)
--3.applypartitionontable/*
CREATETABLEPartitionTable(col1int,col2char(10))ONmyRangePS1(col1)
select*fromsys.partition_functions
select*fromsys.partition_schemes
select*fromsys.partition_range_values
--checkrowsoneverypartitionselect*fromsys.partitionswhereobject_id=*/
BEGINTRANSACTION
CREATECLUSTEREDINDEX[ClusteredIndex_on_myRangePS1]ON[dbo].[factCharge]([DateKey]
)WITH(SORT_IN_TEMPDB=OFF,IGNORE_DUP_KEY=OFF,DROP_EXISTING=OFF,ONLINE=OFF)ON[myRangePS1]([DateKey])
DROPINDEX[ClusteredIndex_on_myRangePS1]ON[dbo].[factChargeBak]WITH(ONLINE=OFF)
COMMITTRANSACTION
--=======================SQLCDC====================================USEAdventureWorksDW;GO
EXECUTEsys.sp_cdc_enable_db;--啟用數(shù)據(jù)庫對(duì)CDC的支持GOEXECsys.sp_cdc_enable_table"dbo","FactInternetSales",@role_name=NULL,@supports_net_changes=0;--啟用某個(gè)表對(duì)CDC的支持GO
SELECTname,is_tracked_by_cdcFROMsys.tablesWHEREnameLIKE("fact%")
INSERTINTOFactInternetSales
VALUES(484,1127,1139,1134,18759,1,100,6,"SO75124",1,1,1,21.9800,21.9800,0,0,8.2205,8.2205,21.9800,1.7584,0.5495,NULL,NULL)INSERTINTOFactInternetSales
VALUES(486,1127,1139,1134,18759,1,100,6,"SO75125",1,1,1,21.9800,21.9800,0,0,8.2205,8.2205,21.9800,1.7584,0.5495,NULL,NULL)
UPDATEFactInternetSalesSETPromotionKey=2WHERESalesOrderNumber="SO75124"
DELETEFROMFactInternetSalesWHERESalesOrderNumber="SO75125"SELECT*FROMcdc.dbo_FactInternetSales_CT;
DECLARE@begin_timedatetime,@end_timedatetime,@from_lsnbinary(10),@to_lsnbinary(10);
--Obtainthebeginningofthetimeinterval.SET@begin_time=GETDATE()-1SET@end_time=GETDATE()
--Mapthetimeintervaltoachangedatacapturequeryrange.
SELECT@from_lsn=sys.fn_cdc_map_time_to_lsn("smallestgreaterthanorequal",@begin_time)
SELECT@to_lsn=sys.fn_cdc_map_time_to_lsn("largestlessthanorequal",@end_time)
print@begin_timeprint@end_timeprint@from_lsnprint@to_lsn
SELECT*FROMcdc.dbo_FactInternetSales_CTWHERE__$start_lsnBETWEEN@from_lsnAND@to_lsn
--撤銷SQLServer201*CDC
EXECsys.sp_cdc_disable_table"dbo","FactInternetSales","All"EXECsys.sp_cdc_disable_db
--=======================Convertinttomoney====================================
SELECTREVERSE(SUBSTRING(REVERSE(CONVERT(varchar,CONVERT(money,123456789),1)),4,30))RMB
擴(kuò)展閱讀:SQL的一些用法小結(jié)
SQL的一些用法小結(jié)(精彩實(shí)用)
1.模糊查詢:select*from表名where查詢字段like"%biao_"%通配符--匹配任意字符_通配符--匹配單個(gè)字符
2.字符串的連接(||):select字段1||","||字段2別名from表名輸出:字段1,字段2
3.查找非空項(xiàng):select*from表名where字段isnotnull4.集合查詢:
union返回兩個(gè)查詢的結(jié)果并去除其中的重復(fù)部分:select字段1from表1unionselect字段1from表2
unionall與union一樣對(duì)表進(jìn)行了合并但是它不去掉重復(fù)的記錄:select字段1from表1unionallselect字段1from表2
intersect(相交)返回兩個(gè)表中共有的行:select字段1from表1intersectselect字段1from表2
mimus(相減)返回的記錄是存在于第一個(gè)表中但不存在于第二個(gè)表中的記錄例:select字段1from表1mimusselect字段1from表25.從屬運(yùn)算(in,between)
select*from表where字段in("值1","值2",-----)----括號(hào)內(nèi)是數(shù)字則不需要用引號(hào)
select*from表where字段betweenMinandMax二.函數(shù)
1.count:該函數(shù)將返回滿足WHERE條件子句中記錄的個(gè)數(shù)selectcount(*)from表where條件2.sum返回某一列的所有數(shù)值的和selectsum(字段)from表3.avg可以返回某一列的平均值selectavg(字段)from表
4.max(min)取得某一列中的最大(小)值selectmax(字段)from表
select*from表where字段=min(字段)
@_@(太多了,不一一列舉了,弄些自己喜歡的^_^)----------------5.user該函數(shù)返回當(dāng)前使用數(shù)據(jù)庫的用戶的名字selectuser[from表]三.子句
1.groupby用于分組
selectsum(字段1)from表groupby字段2having條件------按照字段2進(jìn)行分組顯示
2.having在分組中設(shè)置條件
四.子查詢(子查詢的條件可以關(guān)聯(lián)主表和子表)
select*from表1where字段=(select字段from表2條件)---子查詢的結(jié)果必須是唯一
select*from表1where字段in(select字段from表2條件)----子查詢的結(jié)果不唯一
select*from表1whereexists(select........)-----exists返回trueorfalse五.精彩語句:
insertinto表1(字段1,字段2....)select字段1,字段2.....from表2條件-----復(fù)制表六.創(chuàng)建和操作表1.創(chuàng)建表:CREATETABLEtable_name(field1datatype[NOTNULL]
field2datatype[NOTNULL]
field3datatype[NOTNULL]...)
2.ALTERTABLE語句可以幫助你做兩件事-加入一列到已經(jīng)存在的表中-修改已經(jīng)存在的表中的某一列
ALTERTABLE語句的語法如下
ALTERTABLEtable_name-------修改一列3.刪除表和數(shù)據(jù)庫:
DROPTABLEtable_nameDROPDATABASEdatabase_name4.創(chuàng)建臨時(shí)表:
createtable#table_name(field1datatype,
.fieldndatatype七,存貯過程:創(chuàng)建存貯過程的語法:
createprocedureprocedure_name[[(]@parameter_name
datatype[(length)|(precision[,scale])[=
default][output]-----------參數(shù)
[,@parameter_name
datatype[(length)|(precision[,scale])[=default][output]]...[)]][withrecompile]asSQL_statements運(yùn)行存貯過程的EXECUTE命令的語法:execute[@return_status=]procedure_name
[[@parameter_name=]value
|------------參數(shù)值
[@parameter_name=]@variable[output]...]][withrecompile]八.SQLSERVER提供的全局變量:
在使用存儲(chǔ)過程的時(shí)候你可以自己定義全局變量是非常有用的SQLSERVER也提供
了幾種系統(tǒng)全局變量對(duì)于數(shù)據(jù)庫的系統(tǒng)用戶來說它可能是有用的下表中給出了這些變
量的全部清單你可以在SQLSERVERSYSTEM10的文檔中找到它變量名作用
@@char_convert如果字符轉(zhuǎn)換成功時(shí)其值為0@@client_csid客戶機(jī)所使用字符集的
ID@@client_csname客戶機(jī)的字符集的名字
@@connections從SQLServer啟動(dòng)以來的登錄次數(shù)
@@cpu_busy從SQLServer啟動(dòng)以來的CPU忙的時(shí)間總數(shù)@@error錯(cuò)誤的狀態(tài)
@@identity插入到確定列中的最后一個(gè)值@@idle從SQLServer啟動(dòng)以來的總時(shí)間數(shù)@@io_busySQLServer用于I/O操作的時(shí)間
@@isolation當(dāng)前的Transact-SQL程序的隔離級(jí)別@@langid定義了本地語言的ID號(hào)@@language定義了本地語言的名稱@@maxcharlen字符的最大長度
@@max_connections可與SQLSERVER進(jìn)行連接的最大數(shù)量@@ncharsizeAveragelengthofanationalcharacter.@@nestlevel當(dāng)前進(jìn)程的嵌套級(jí)別
@@pack_received從SQLServer啟動(dòng)以來的讀入的數(shù)據(jù)包的數(shù)量@@pack_sent從SQLServer所發(fā)出的輸出包的數(shù)量
@@packet_errors從SQLServer啟動(dòng)以來產(chǎn)生錯(cuò)誤的數(shù)量@@procid當(dāng)前正在運(yùn)行的存儲(chǔ)過程的ID號(hào)@@rowcount上一個(gè)命令所涉及的行數(shù)
@@servername本地localSQLServer的名字@@spid當(dāng)前正在處理的進(jìn)程ID號(hào)@@sqlstatus存儲(chǔ)狀態(tài)信息
@@textsize由SELECT語句所返回的文本映像的最大長度@@thresh_hysteresisChangeinfreespacerequiredtoactivateathreshold.@@timeticksNumberofmicrosecondspertick.@@total_errors在讀寫過程中產(chǎn)生的錯(cuò)誤數(shù)
@@total_read在SQLServer啟動(dòng)以來讀磁盤的次數(shù)@@total_write在SQLServer啟動(dòng)以來寫磁盤的次數(shù)@@tranchained在Transact-SQL程序中當(dāng)前事務(wù)的模式@@trancount事務(wù)的嵌套級(jí)別
@@transtate當(dāng)一個(gè)語句運(yùn)行后當(dāng)前事務(wù)的狀態(tài)@@version當(dāng)前SQLServer的版本日期
友情提示:本文中關(guān)于《SQL用法總結(jié)》給出的范例僅供您參考拓展思維使用,SQL用法總結(jié):該篇文章建議您自主創(chuàng)作。
來源:網(wǎng)絡(luò)整理 免責(zé)聲明:本文僅限學(xué)習(xí)分享,如產(chǎn)生版權(quán)問題,請(qǐng)聯(lián)系我們及時(shí)刪除。