一些SQLServer存储过程参数及举例
MicrosoftincludedseveralhundredstoredproceduresinthevariousversionsofMicrosoftSQLServerandithasdocumentedagoodpercentageofthem.Butmanystoredproceduresremainundocumented.SomeareusedwithintheEnterpriseManagerGUIinSQL2000andwerenotintendedtobeusedbyotherprocesses.Microsofthasslatedsomeofthesestoredprocedurestoberemoved(ortheyhavebeenremoved)fromfutureversionsofSQLServer.Whilethesestoredprocedurescanbeveryusefulandsaveyoulotsoftime,theycanbechangedatanytimeintheirfunctionortheycansimplyberemoved.
ThechartbelowshowsthatwhilemanyoftheprocedureshavebeencarriedthroughfromoneversionofMicrosoftSQLServertoanother,newstoredprocedureshavebeenintroduced,andsomehavebeenremovedfromtheinstallpackage.Most,ifnotall,oftheproceduresrequiretheusertobeamemberofthesysadminfixedserverroleinordertoexecutetheprocedures.Thestoredproceduresthatinteractwiththefilesystemalsorequirethattheuserexecutingtheprocedure(aswellasSQLServer"sserviceaccount)haveaccesstothefile/folder.
sp_executeresultset
Microsoftremovedthishandylittleprocedurecalledsp_executeresultsetfromSQLServerinSQLServer2005.ItallowsyoutogeneratedynamicSQLcodeontheflybyusingaSELECTquery.Then,theresultingSQLcommandswillbeexecutedagainstthedatabase.Itpermitsyoutocreateasinglepieceofcodethatcan,inasinglestep,findthenumberofrecordsineverytableinyourdatabase(astheexampleshows).Thisisanundocumentedstoredprocedureandthereisnowayofknowingwhyitwasremoved.But,alas,thishandyutilityisgone.
execsp_execresultset"SELECT""SELECT""""""+name+"""""",
count(*)FROM""+name
fromsysobjects
wherextype=""U"""
sp_MSforeachdb/sp_MSforeachtable
Twoprocedures,sp_MSforeachdbandsp_MSforeachtable,arewrappersaroundacursor.TheyallowyoutoexecuteT-SQLcodeagainsteachdatabaseonyourSQLServerandeachtablewithinthecurrentdatabase,respectively.Youcannot,however,useansp_MSforeachtablecommandwithinansp_MSforeachdbcommandinSQL2000andprior.Thecursornamethatwasusedwithinthoseprocedureswasthesame(hCForEach)andwouldthereforereturnanerrorsayingthatthecursornamewasalreadyinuseforeachexecutionofthesp_MSforeachtable.InSQLServer2005,Microsoftresolvedthisissue.Inorderto"next"thecommand,youmusttelloneoftheproceduresitwillbeusingadifferentreplacementcharacterotherthanthedefaultquestionmark.Ichangethereplacementcharacterinthedatabasecommandbecauseit"seasier.
Printeachtablenameinthecurrentdatabase.
execsp_MSforeachtable"print""?"""
Printeachdatabaseonthecurrentserver.
execsp_MSforeachdb"print""?"""
Printeachtableonthecurrentserver.
execsp_MSforeachdb"use[@]execsp_MSforeachtable""print
""""@.?""""""","@"
sp_readerrorlog/xp_readerrorlog
Thestoredproceduresp_readerrorlogactuallycomesintwoforms.Eachworksthesame;oneissimplyawrapperforthesecond.Thewrapperstoredprocedureissp_readerrorloganditcallsxp_readerrorlog.Bothhavefourinputparameters,butonlythefirsttwoareusefultous.Thefirstparameterestablishesthefilenumberthatyouwishtoview.Thesecondisthelogtoview(1ornullforERRORLOG,2forSQLAgentLog).ThisallowsyoutoviewyourerrorlogsquicklyandeasilyinsteadofhavingtolookatthebloatedlogviewerthatnowcomeswithSQLServer2005andSQL2008.
ViewthecurrentSQLERRORLOGfile.
execsp_readerrorlog
execsp_readerrorlog0,1
ViewthePriorSQLAgentLogfile.
execsp_readerrorlog1,2
xp_create_subdir
IntroducedinSQLServer2005,thexp_create_subdirstoredprocedureisveryhandybecauseyoucanuseittocreatefoldersonSQLServer"sharddriveoronanetworksharefromwithinT-SQL.
execxp_create_subdir"c:\MSSQL\Data"
xp_delete_file
Usethexp_delete_filestoredprocedureintroducedinSQLServer2005todeletefilesfromSQLServer"sharddriveoranetworksharefromwithinT-SQL.
xp_dirtree
Thexp_dirtreeprocedureallowsyoutoviewthefoldertreeand/orfilelistbeneathafolder.Thisprocedurehasseveralparametersthatcontrolhowdeeptheproceduresearchesandwhetheritreturnsfilesandfoldersorfoldersonly.Thefirstparameterestablishesthefoldertolookin.(Recommendation:DonotrunthisprocedureagainsttherootofthedrivethatWindowsisinstalledonbecauseitwilltakesometimetogeneratethetreeandreturnthedata.)Thesecondparameterlimitsthenumberofrecursivelevelsthattheprocedurewilldigthrough.Thedefaultiszerooralllevels.Thethirdparametertellstheproceduretoincludefiles.Thedefaultiszeroorfoldersonly,avalueof1includesfilesintheresultset.Specifyingathirdvaluenotequaltozerowilladdanadditionalcolumntotheoutputcalledfilewhichisabitfieldshowingtheentryinafolderorfile.
Getthefulldirectorytree.
execxp_dirtree"d:\mssql\"
Getthefirsttwolevelsofthedirectorytree.
execxp_dirtree"d:\mssql\",2
Getthefirstthreelevelsofthedirectorytree,includingfiles.
execxp_dirtree"d:\mssql\",3,1
xp_fileexist
ThisSQLServerstoredprocedure,xp_fileexist,isusedtodetermineifafileexistsonSQLServer"sharddriveoronanetworkshare.Itisextremelyusefulinstoredproceduresthatloaddatafromflatfiles.Itallowsyoutocheckandseeifthefileexistsbeforeattemptingtoblindlyloadthefile.Theprocedurehastwoparameters.Usethefirstparametertodetermineifthefileorfolderyouwantexists.Thesecondisanoutputparameter,whichwhenspecified,returnsa1or0ifthefileexistsordoesnot.
Withouttheparameter.
execxp_fileexist"c:\importfile.csv"
Withtheparameter.
DECLARE@file_existsint
execxp_fileexist"c:\importfile.csv",@file_existsOUTPUT
SELECT@file_exists
xp_fixeddrives
Theprocedurexp_fixeddrivesisoneofthemostusefulprocedures.Itpresentsalistofalldrivelettersandtheamountoffreespaceeachdrivehas.Theparameterhasasingleoptionalinputparameterthatcanfiltertheresultsbydrivetype.Avalueof3willreturnallmassstoragedevices(CD-ROM,DVD,etc.);avalueof4willreturntheharddrives;whileavalueof2willreturnremovablemedia(USBthumbdrives,flashdrives,etc.).
Returnalldrives.
execxp_fixeddrives
Returnharddrivesonly.
execxp_fixeddrives2
xp_getfiledetails
Theprocedurexp_getfiledetailsisanotherextremelyusefulprocedure,whichwaslastavailableinSQLServer2000.Thisprocedurereturnssize,dateandattributeinformationaboutthefilespecified,includingdateandtimescreated,accessedandmodified.
execxp_getfiledetails"c:\filetoload.csv"
xp_getnetname
Theprocedurexp_getnetnamereturnsthenameofthephysicalmachinewhereMicrosoftSQLServerisinstalled.Youcanhavethemachinenamereturnedasarecordsetorasavariable.
Withouttheparameter.
execxp_getnetname
Usingtheparameter.
DECLARE@machinenamesysname
execxp_getnetname@machinenameOUTPUT
select@machinename
xp_loginconfig
ThisSQLServerstoredprocedurewilltellyousomebasicauthenticationinformationabouttheuserexecutingit.Ittellsyoutheauthenticationmethod(WindowsversusSQLLogin),thedefaultdomainoftheserver,theauditlevel,aswellassomeinternalseparatorinformation.
execxp_loginconfig
xp_makecab
BackinSQLServer2000,MicrosoftgaveustheabilitytocompressOSfilesdirectlyfromT-SQLwithouthavingtoshellouttoDOSviaxp_cmdshellandrunthird-partysoftware,likepkziporwinzip.Thatcommandwasxp_makecab.Itallowsyoutospecifyalistoffilesyouwanttocompressaswellasthecabfileyouwanttoputthemin.Itevenletsyouselectdefaultcompression,MSZIPcompression(akintothe.zipfileformat)ornocompression.Thefirstparametergivesthepathtothecabfileinwhichyouwanttocreateoraddfilesto.Thesecondparameteristhecompressionlevel.Thethirdparameterappliesifyouwanttouseverboselogging.Startingwiththefourthparameterandondownarethenamesofthefilesyouwanttocompress.Inmytesting,Iwasabletopass45filenamestobecompressedtotheextendedstoredprocedure,whichmeansthatitisaveryflexiblesolutiontoyourdatacompressionrequirements.
execxp_makecab"c:\test.cab","mszip",1,"c:\test.txt","c:\test1.txt"
xp_msver
Theprocedurexp_msverisveryusefulwhenlookingforsysteminformation.Itreturnsawealthofinformationaboutthehostoperatingsystem--theSQLversionnumber,language,CPUtype,copyrightandtrademarkinformation,MicrosoftWindowsversion,CPUcountandaffinitysettings,physicalmemorysettingsandyourproductkey.Thisprocedurehasmanyinputparametersthatallowyoutofilterdowntherecordsthatarereturned.Eachparameterisasysnamedatatype,whichacceptsthenameofoneoftherecords.Ifanyparametersarespecified,onlytherowsspecifiedasaparameterarereturned.
Nofilterspecified.
execxp_msver
ReturnonlyPlatformandCommentsrecords.
execxp_msver"Platform","Comments"
xp_get_mapi_profiles
Thexp_get_mapi_profilesprocedureassistsyouinconfiguringSQLMail.Whenexecuted,itwillcalltoWindowsviatheSQLMailcomponentofSQLServeranddisplayalistofavailableMAPIprofilesthatareconfiguredinOutlookanditspecifieswhichprofileisthedefaultprofile.Ifitdoesn"tdisplayanyrecords,theneitherOutlookisnotconfiguredcorrectlyorSQLServerisnotrunningunderadomainaccountwithOutlookprofilesconfigured.InordertousethisprocedureinSQLServer2005orSQLServer2008,youmustenablethe"SQLMailXPs"optionintheSurfaceAreaConfigurationtoolorwithinthesp_configureprocedure.
execxp_get_mapi_profiles
xp_subdirs
Thexp_subdirsproceduredisplaysasubsetoftheinformationavaialblethroughxp_dirtree.Xp_subdirswilldisplayallthesubfoldersinagivenfolder.Itcanbeveryhandywhenyouarebuildingadirectorytreewithinatabledynamicallyandyoudonotwanttoworryabouttheextraparametersofthexp_dirtreeprocedure.
execxp_subdirs"d:\mssql"
xp_test_mapi_profiles
Theprocedurexp_test_mapi_profilesisanotherundocumentedstoredprocedurethatisveryusefulwhenyouaresettingupSQLMail.Itwillstart,thenstop,aMAPIsessiontoensurethatMAPIisconfiguredcorrectlyandworkingwithintheconfinesofMicrosoftSQLServer.IshouldnotethatitdoesnotverifythemailserverconfigurationwithintheMAPIclient(Outlook)nordoesitsendatestmessage.
Theprocedureacceptsasingleinputparameter.ThatparameteristhenameoftheMAPIprofileyouwishtotest.Likethexp_get_mapi_profilesprocedure,forthisstoredproceduretofunctioninSQLServer2005andSQLServer2008,youmustenablethe"SQLMailXPs"optionintheSurfaceAreaConfigurationtoolorwithinthesp_configureprocedure.
WhenworkingwiththeSQLMailstoredprocedures,beawarethatSQLMailisstillslatedforremovalfromtheMicrosoftSQLServerplatform.Thatmeanstheproceduressp_get_mapi_profilesandxp_test_mapi_profilesareslatedforremoval,astheyarepartoftheSQLMailsubsystem.YoushoulddoallmailworkonSQLServer2005andlaterusingDatabaseMailinsteadofSQLMailtoensurecodeportabilitywithfutureversionsofSQLServer.MicrosoftinitiallyslatedSQLMailforremovalinSQLServer2008,however,basedonitsinclusioninthecurrentbetarelease,itsfutureinSQLServer2008isunknown.
xp_unpackcab
Alongwiththexp_makecabprocedurecomesthexp_unpackcabextendedstoredprocedure,anditdoesjustwhatitsays:Itextractsfilesfromcabfiles.Thefirstparamateristhecabfile,thesecondisthepathyouwanttoextracttoandthethirdisverboselogging.Afourthparamaterletsyouspecifythe"extractto"filename.
execxp_unpackcab"c:\test.cab","c:\temp\",1
WhilethisisnotintendedtobeacompletelistoftheundocumentedstoredproceduresinSQLServer,itdoesprovideareferencepointformanyoftheseprocedureswiththehopeofmakingthelivesoftheSQLServeradministratorseasier.Remember,youshouldnevercountontheseproceduressurvivingfromoneSQLServerversiontothenext,norshouldyouexpecttheircodebasetoremainthesamebetweenversions.Thatsaid,gocodeandenjoy.
AllinformationprovidedaboutMicrosoftSQLServer2008(Katmai)isbasedonbetaedition10.0.1019ofthesoftwareandissubjecttochangewithoutnotice.
相关文章
- 如何把sqlserver数据迁移到mysql数据库及需要注意事项
- 精通SQL Server数据类型:提升数据存储与处理能力(sqlserver数据类型)
- SQLServer测试:如何确保数据库性能和安全性?(sqlserver测试)
- 聪明的选择:拥有自带SQLServer的体验(自带sqlserver)
- 日志深入了解SQL Server日志:从查看到管理(查看sqlserver)
- 新版SQLServer:激发更高数据处理能力(新版sqlserver)
- 免费云SQLServer:拥有更多智能应用的新时代(免费云sqlserver)
- 优化SQLServer系统性能:提升锁机制(sqlserver锁优化)
- 存储过程如何快速使用SqlServer调用存储过程(sqlserver 调用)
- 解决SQL Server配置困难,优化系统性能(sqlserver 设置)
- 数据转移 sqlserver表中数据转移: 高效方式保ise你的数据 (sqlserver表中的)
- 使用SQLServer电子版轻松解决数据存储问题(sqlserver电子版)
- . SQL Server数据库:月度管理(sqlserver月 1)
- 妙用SQL Server:插入数据的正确姿势(sqlserver插数据)
- 存储过程如何使用SQLServer编写专业的存储过程(sqlserver怎么写)
- 是数据库中心SQL Server:让电脑成为数据库核心(sqlserver对电脑)
- SqlServer下的多叉树结构实现(sqlserver多叉树)
- SQL Server架构探索:助力数据存储自动化(sqlserver 架构)
- SqlServer设置双主键:实现安全可靠的数据存储(sqlserver双主键)
- SQL Server去除非零值的技巧(sqlserver去掉0)
- 使用SQL Server打造稳定可靠的主机系统(sqlserver主机)
- SqlServer主键标识:索引中枢和表关联(sqlserver主id)
- SQLserver 技术专家谈数据库未来展望(sqlserver 专家)
- 题:SQLServer:优秀的数据库解决方案(sqlserver 下标)
- 度报表SQLServer上的年度报表制作实录(sqlserver上年)
- yDIY:学会用SQLServer构建你的专属应用(sqlserver di)
- 韩立刚成功掌握SQLServer 技术,实现数据库自动化管理(韩立刚sqlserver)
- 使用计算机SQL Server实现数据库管理(计算机sqlserver)
- 一些SQLServer存储过程参数及例子