|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
客户还是可以使用DBaaS系统所能提供的所有能力。数据库云服务消除了组织对专职人员、本地数据库存储设备的需要。他们不必安装、配置和维护任何软硬件。oracle
仍是有良多的分歧,转贴以下:http://www.bristle.com/Tips/SQL.htm#Oracle%20Tips
TableofContents:OracleTipsSQLTipsSELECT*andmoreMaterializedViewPL/SQLTipsSQLNavigatorTipsSeeAlsoMSSQLServerTipsSQLTipsDynamicSQLinaStoredProcedureSQLEnterpriseManagerTipsKeyboardShortcutsSQLGeneratingSQLSeeAlsoDifferencesBetweenOracleandMSSQLServerConceptsandTerminologyDataTypesLimitsOperatorsBuilt-InFunctionsDifferencesinSQLSyntaxDifferencesinSQLSemanticsDifferencesinManagingDatabasesDifferencesinManagingDatabaseObjectsDifferencesinManagingUsersDifferencesinIntegrationwithMSADO,RDO,etc.MiscellaneousDifferencesSeeAlsoDetailsofTips:OracleTipsSQLTips
ThissectioncontainstipsonstandardSQL(StructuredQueryLanguage)statementsinOracle.
SELECT*andmore
LastUpdated:6/6/1999
Appliesto:Oracle7.3,8(andprobablyearlierversions)
Toselectallcolumnsofatable:
select*fromtable
However,toselectallrealcolumns,plusapseudo-columnlike"user":
selecttable.*,userfromtable
Thefollowingdoesnotwork:
select*,userfromtable
--Fred
MaterializedView
LastUpdated:1/7/2002
Appliesto:Oracle8+
Oracle8iintroducedanewfeaturecalleda"materializedview".Youdefineitjustlikeanyotherview,exceptthatyouaddthekeywordMATERIALIZED:
CREATEMATERIALIZEDVIEWview_name
Amaterializedviewislikeacombinationofatableandaview.Likeaview,itisdefinedasalogicalviewintothedataofoneormoretables.Whenyouupdatethetables,subsequentqueriesoftheviewseetheupdateddata.However,likeatable,itsdataisstoredinthedatabase.Also,likeatable,itisfasterifyoudefineindexesforit.
Aregularviewisstoredasamappingofdatafromtables.Whenyoumodifythedatainthetables,theviewiscompletelyignored.Whenyouaccesstheview,itjoinsthedatacurrentlyinthetables,andreturnsthedatayourequested.Amaterializedviewisstoredassuchamappingalongwithacopyoftheactualdatafromthetables.Whenyoumodifythedatainthetables,theviewscopyofthedataisalsoupdated.Whenyouaccesstheview,thedataisdrawndirectlyfromthecopy.
Thusamaterializedviewmakestableupdatesalittleslower,butmakesviewqueriesmuchfaster.Italsoconsumesadditionalspaceinthedatabase.
Youcouldaccomplishthesameeffectbydefininganadditionaltableinsteadoftheview,andusingtriggersonthecomponenttablestoupdateiteachtimetheyarechanged.However,usingamaterializedviewismoreconvenient,moreefficient,andclearertothenextpersonwhohastomaintainyourdatabase.
ThankstoAndyGlickforsendingmeasampleofamaterializedviewfromhisapplication!
--Fred
PL/SQLTips
ThissectioncontainstipsonPL/SQLstatements--theOracle"procedurallanguage"supersetofSQLthatyouusetowritestoredprocedures.
SQLNavigatorTips
ThissectioncontainstipsontheSQLNavigatortoolbyQuestSystems.ItisagraphicalfrontendtotheOracledatabase,allowingyoutocreate,delete,view,andmodifyallOracleobjects:tables,views,storedprocedures,etc.
SeeAlso
LastUpdated:6/6/1999
Appliesto:Oracle7.3+
ThefollowingaregoodsourcesofinfoaboutOracle:
Koch,George,andKevinLoney.Oracle8,TheCompleteReference.BerkeleyCA:ForOraclePressbyOsborneMcGraw-Hill,1997.ISBN0-07-882396-X.
ThisbookincludesintroductorydatabaseconceptsaswellasacompletereferencetoOracleSQLandPL/SQLstatements.ThecompanionCDcontainsacompletecopyofthebook,soyoucanreaditon-line,searchit,etc.AnyoftheOReillybooks.IvebeenveryimpressedbyalloftheOReillybookssincemyearlyUnixandX-Windowsdaysinthe80s,andtheyhaveacompleteseriesonOracle,coveringPL/SQL,thestandardpackages,etc.
--Fred
MSSQLServerTipsSQLTips
ThissectioncontainstipsonSQL(StructuredQueryLanguage)statementsinMSSQLServer.
DynamicSQLinaStoredProcedure
LastUpdated:2/7/1999
Appliesto:MSSQLServer6.5+
AtypicaltradeoffforadatabaseapplicationisdynamicSQL(SQLcommandsembeddedintheapplication--forflexibility)vs.storedprocedures(pre-compiledSQLproceduresstoredinthedatabaseandinvokedbynamefromtheapplication--forspeedandcontroloverwhatSQLstatementsgetexecuted).However,youcanhavethebestofbothworldsbyusingdynamicSQLinsideyourstoredprocedures.Inastoredprocedure,youcanusetheEXECstatementtoexecuteastringofSQLstatementsthatyoubuiltdynamicallyinthestoredprocedureorreadfromthedatabaseoranyotherdatasource.
ThankstoSteveRhoadsforthistip.
--Fred
SQLEnterpriseManagerTips
ThissectioncontainstipsontheSQLEnterpriseManagertool.Itisagraphicalfrontendtothedatabase,allowingyoutocreate,delete,view,andmodifyallMSSQLServerobjects:tables,views,storedprocedures,etc.
KeyboardShortcuts
LastUpdated:6/20/1999
Appliesto:MSSQLServer7.0
HereisalistofsomeofthemoreusefulshortcutkeysinSQLEnterpriseManager.
KeyFunctionF1HelponSQLEnterpriseManagerShift-F1HelponsyntaxofcurrentSQLstatementCtrl-EExecuteselectedtextinQueryAnalyzerCtrl-RHide/showresultspaneinQueryAnalyzer
Obviously,thislistisfarfromcomplete.Pleasefeelfreetomailmeyourfavoriteshortcuts.Illaddtothislistastimepermits.
Seealso:WindowsShortcutKeys
--Fred
SQLGeneratingSQL
LastUpdated:2/7/1999
Appliesto:MSSQLServer6.5+
Toautomatetediousdatabasemaintenancechores,youcanuseSQLstatementstogenerateSQLstatementsthatdoyourmaintenanceforyou.Forexample,tochangethepermissionsonallstoredproceduresinadatabase,youcanuseaSELECTstatementlike:
SELECTGRANTEXECUTEON+name+TOPUBLICGOFROMsysobjectsWHEREtype=P
TheoutputofthisSELECTstatementisaseriesofalternatingGRANTandGOstatements,onepairperstoredprocedures,forallstoredproceduresinthedatabase.Thenyoucopythatoutputasyournextsetofcommandsandexecuteit.
Note:BesuretoleavethelinebreakbeforethewordGO.Itisrequiredtostartonanewline,aftertheGRANTstatement.
ThankstoSteveRhoadsforthistip.
--Fred
SeeAlso
LastUpdated:6/6/1999
Appliesto:MSSQLServer6.5+
ThefollowingaregoodsourcesofinfoaboutMSSQLServer:
MSSQLServerbooksontheMSDNLibraryCD.
--Fred
DifferencesBetweenOracleandMSSQLServerConceptsandTerminology
LastUpdated:4/24/2001
Appliesto:Oracle7.3+,MSSQLServer6.5+
ThefollowingtableshowssomedifferencesinconceptsandterminologybetweenOracleandMSSQLServer:
Concept/TermOracleMSSQLServerDatabaseenginedatabasedatabaseserverDatabase(collectionoftables)schemadatabaseRoles/GroupsrolesgroupsDatabaseadminstratoraccount,databaseownerdbasa,dboDataaboutthedatabaseDataDictionary
-oneperserverDatabaseCatalog
-oneperdatabase
"master"database
-oneperserverBlocksandextentsblocksandextentspagesandextentsNetworksoftwareSQL*NetNet-libraryDatastreamprotocolTransparentNetworkSubstrate(TNS)TabularDataStream(TDS)Casesensitivityofnamesoftables,columns,etc.case-insensitivedependsoncharactersortorder,defaultiscase-insensitiveSynonymssupportednotsupportedReadonlytransactionsupportednotsupported
--Fred
DataTypes
LastUpdated:6/6/1999
Appliesto:Oracle7.3+,MSSQLServer6.5+
ThefollowingtableshowsthecorrespondingdatatypesinOracleandMSSQLServer:
DataTypeOracleMSSQLServerFixedLengthStringCHAR(n)
-limit2KBCHAR(n),CHARACTER(n)
-limit255(6.5)
-limit8KB(7.0)VariableLengthStringVARCHAR2(n),VARCHAR(n)
-limit4KBinacolumn
-limit32KBinavariable
-VARCHARisobsolete
VARCHAR(n),CHARVARYING(n),CHARACTERVARYING(n)
-limit255(6.5)
-limit8KB(7.0)IntegerINTEGER,INTEGER(n),SMALLINTINTEGER(4bytes),
INT(4bytes),
SMALLINT(2bytes),
TINYINT(1byte),
BIT(1bit)FixedPointNUMBER,NUMBER(n),NUMBER(n,d),
FLOAT,FLOAT(n),FLOAT(n,d)NUMERIC,NUMERIC(n),NUMERIC(n,d),
DECIMAL,DECIMAL(n),DECIMAL(n,d),
DEC,DEC(n),DEC(n,d),
MONEY,SMALLMONEYFloatingPointDECIMALFLOAT,FLOAT(n),DOUBLEPRECISION,
REAL,DateDATEDATETIME,SMALLDATETIME,TIMESTAMP
-TIMESTAMPauto-updatedBinaryRAW(n)
-limit255bytesBINARY(n),VARBINARY(n),BINARYVARYING(n)
-limit255(6.5)
-limit8KB(7.0)LargeStringLONG,LONGVARCHAR
-limit2GB
-limitonepertablerow
CLOB
-limit4GBTEXT
-limit2GBLargeBinaryLONGRAW
-limit2GB
-limitonepertablerow
BLOB
-limit4GBIMAGE
-limit2GBMulti-bytecharsNCHAR(n)
NVARCHAR(n)
NCLOB
-samelimitsasCHAR,VARCHAR,CLOBNCHAR(n),NATIONALCHAR(n),NATIONALCHARACTER(n)
NVARCHAR(n),NATIONALCHARVARYING(n),NATIONALCHARACTERVARYING(n)
NTEXT,NATIONALTEXT
-samelimitsasCHAR,VARCHAR,TEXTOSFileBFILE<notsupported>RowIdentifierimplicitROWIDcolumn(useanIDENTITYcolumn)SecureOSLabelMLSLABEL,RAWMLSLABEL<notsupported>128-bitUniqueNumber
(UUID,GUID)<notsupported>UNIQUEIDENTIFIER(version7.0only)
--Fred
Limits
LastUpdated:6/14/2000
Appliesto:Oracle7.3+,MSSQLServer6.5+
ThefollowingtableshowsdifferencesinlimitsofOracleandMSSQLServer:
DescriptionOracleMSSQLServerColumnspertable1000250(6.5)
1024(7.0)Rowsizeunlimited1962bytes(6.5)
8060bytes(7.0)
-includespointers,butnotdata,forTEXTandIMAGEcolumnsLONGandLONGRAWcolumnsperrow1(mustbelastcolumn)unlimited(16-bytepointerper)LOB,TEXT,andIMAGEcolumnsperrowunlimited(16-bytepointerper)unlimited(16-bytepointerper)Clusteredindexespertable11Non-clusteredindexespertableunlimited249Columnsperindex1616Indexrowsize2Kbytes900bytesIdentifierLength30chars30chars(6.5)
128chars(7.0)TablesperSELECTunlimited16(6.5)
256(7.0)Sourcecodeperstoredprocedure64KB(6.5)
250MB(7.0)Datatypelimits(seeDataTypes)
--Fred
Operators
LastUpdated:6/7/1999
Appliesto:Oracle7.3+,MSSQLServer6.5+
MostoperatorsarethesameinOracleandMSSQLServer.Herearesomethatdiffer:
DescriptionOracleMSSQLServerStringconcatenationstring1||string2string1+string2
--Fred
Built-InFunctions
LastUpdated:6/7/1999
Appliesto:Oracle7.3+,MSSQLServer6.5+
OracleandMSSQLServeroffermanyofthesamebuilt-infunctions.Forexample,theybothofferABS,EXP,ROUND,UPPER,LOWER,AVG,COUNT,SUM,ASCII,etc.Thefollowingtableshowssomeofthecorrespondingfunctionsthatdonthavethesamename.Foramorecompletelist,see"MigratingOracleApplicationstoSQLServer"
DescriptionOracleMSSQLServerSmallestinteger>=nCEILCEILINGModulusMOD%TruncatenumberTRUNC<none>MaxorminnumberorstringinlistGREATEST,
LEAST<none>TranslateNULLtonNVLISNULLReturnNULLiftwovaluesareequalDECODENULLIFStringconcatenationCONCAT(str1,str2)str1+str2ConvertASCIItocharCHRCHARCapitalizefirstlettersofwordsINITCAP<none>FindstringinstringINSTRCHARINDEXFindpatterninstringINSTRPATINDEXStringlengthLENGTHDATALENGTHPadstringwithblanksLPAD,
RPAD<none>TrimleadingortrailingcharsotherthanblanksLTRIM(str,chars),
RTRIM(str,chars)<none>ReplacecharsinstringREPLACESTUFFConvertnumbertostringTO_CHARSTR,CASTConvertstringtonumberTO_NUMBERCASTGetsubstringfromstringSUBSTRSUBSTRINGCharforchartranslationinstringTRANSLATE<none>DateadditionADD_MONTHor+DATEADDDatesubtractionMONTHS_BETWEENor-DATEDIFFLastdayofmonthLAST_DAY<none>TimezoneconversionNEW_TIME<none>NextspecifiedweekdayafterdateNEXT_DAY<none>ConvertdatetostringTO_CHARDATENAME,CONVERTConvertstringtodateTO_DATECASTConvertdatetonumberTO_NUMBER(TO_CHAR(d))DATEPARTDateroundROUNDCONVERTDatetruncateTRUNCCONVERTCurrentdateSYSDATEGETDATEConverthextobinaryHEXTORAWCASTConvertbinarytohexRAWTOHEXCONVERTIfstatementinanexpressionDECODECASE...WHEN
orCOALESCEUsersloginidnumberornameUID,USERSUSER_ID,SUSER_NAMEUsersdatabaseidnumberornameUID,USERUSER_ID,USER_NAMECurrentuserUSERUSER
--Fred
DifferencesinSQLSyntax
LastUpdated:3/21/2001
Appliesto:Oracle7.3+,MSSQLServer6.5+
ThefollowingtableshowsthedifferentsyntaxusedinOracleandMSSQLServerforthesameSQLoperations:
DescriptionOracleMSSQLServerLeftOuterJoinWHEREcolumn1=column2(+)FROMtable1LEFTOUTERJOINtable2ONtable1.column1=table2.column2
Note:Thefollowingsyntaxisalsosupported,butisnolongerrecommended:
WHEREcolumn1*=column2RightOuterJoinWHEREcolumn1(+)=column2FROMtable1RIGHTOUTERJOINtable2ONtable1.column1=table2.column2
Note:Thefollowingsyntaxisalsosupported,butisnolongerrecommended:
WHEREcolumn1=*column2FullOuterJoinFROMtable1FULLOUTERJOINtable2ONtable1.column1=table2.column2SELECTwithoutFROMSELECThelloworldFROMDUALSELECThelloworldSELECTdataintoatableCREATETABLEASSELECT...SELECT...INTOIntersectionof2SELECTSSELECT...INTERSECTSELECT...SELECT...WHEREEXISTS(SELECT...)Subtractionof2SELECTSSELECT...MINUSSELECT...SELECT...WHERENOTEXISTS(SELECT...)INSERTintoaJOININSERTINTOSELECT...CreateaVIEWandINSERTINTOit.UPDATEdatainaJOINUPDATESELECT...CreateaVIEWandINSERTINTOit.UPDATEonetablebasedoncriteriainanothertable<notsupported>UPDATEtableFROM...DELETErowsfromonetablebasedoncriteriainanothertable<notsupported>DELETEFROMtableFROM...DROPacolumnfromatable<notsupporteduntilOracle8i>ALTERTABLEtable_nameDROPCOLUMNcolumn_nameReadonlyVIEWCREATEVIEW...WITHREADONLYGRANTSELECT...SavepointSAVEPOINTSAVETRANSACTIONTablelockLOCKTABLE...INSHAREMODESELECT...table_name(TABLOCK)ExclusivetablelockLOCKTABLE...INEXCLUSIVEMODESELECT...table_name(TABLOCKX)ReservingindexspacePCTFREE=0FILLFACTOR=100DeclaringalocalvariableDECLAREvarnametype;DECLARE@varnametypeInitializingalocalvariableDECLAREvarnametype:=value;<notsupported>DeclaringaconstantDECLAREvarnameCONSTANTtype:=value;<notsupported>Assigningtoavariablevarname:=value
SELECTvalueINTOvarnameSET@varname=value
SELECT@varname=valueAssigningtoavariablefromacursorFETCHcursornameINTOvarnameFETCHNEXTFROMcursornameINTOvarnameDeclaringacursorCURSORcurname(params)
ISSELECT...;DECLAREcurnameCURSORFORSELECT...IfstatementIF...THEN
ELSIF...THEN
ELSE
ENDIFIF...
BEGIN...END
ELSEBEGIN...ENDWhileloopWHILE...LOOP
ENDLOOPWHILE...
BEGIN...ENDOtherloopsFOR...ENDLOOP
LOOP...ENDLOOP<notsupported>LoopexitEXIT,EXITWHENBREAK,CONTINUEPrintoutputDBMS_OUTPUT.PUT_LINEPRINTRaiseerrorRAISE_APPLICATION_ERRORRAISERRORStatementterminatorSemi-colon(;)<nonerequired>
ThankstoTomJohnstonforcatchingamistakeinthistip.IhadtheFROMDUALinthewrongcolumn.
--Fred
DifferencesinSQLSemantics
LastUpdated:6/6/1999
Appliesto:Oracle7.3+,MSSQLServer6.5+
ThefollowingtableshowssomesemanticdifferencesbetweenOracleandMSSQLServer:
DescriptionOracleMSSQLServerCommitExplicitCOMMITstatementrequiredAutomaticcommitunlessSETIMPLICIT_TRANSACTIONSONReadinguncommitteddataDatabasedoestemporaryinternalrollbacktoreconstructmostrecentlycommitteddataforreader.Dependingonoptions,readerasallowedtoreaduncommitteddata,orisforcedtowaitforwritertocommitorrollback.ReleasingcursordataCLOSECURSORreleasesalldata.Youcantre-open.CLOSECURSORdoesnotreleasedata.YoumustexplicitlycallDEALLOCATECURSOR.Untilthen,youcanre-openthecursor.ImplicitdataconversioninastatementlikethefollowingwherevcisacolumnoftypeVARCHAR2:
SELECT*FROMperson
WHEREvc=123
Aseachrowisfetchedfromthetable,anattemptismadetoconvertittoanumberforthecomparisonwith123.Ifanyrowcontainsavaluethatcannotbeconvertedtoanumber,aruntimeerroroccurs.Thenumber123isconvertedtothestring123once,andthenthedataisfetchedfromthetable.Ifanyrowcontainsavaluethatcannotbeconvertedtoanumber,itsimplydoesntmatch123andisskippedwithoutanyerror.ConversiontoNULLSettingaVARCHAR2columnto(theemptystring)makesitNULL.SettingaVARCHARcolumntomakesittheemptystring(notNULL).
--Fred
DifferencesinManagingDatabases
LastUpdated:6/6/1999
Appliesto:Oracle7.3+,MSSQLServer6.5+
ThefollowingtableshowssomedifferencesinhowdatabasesaremanagedinOracleandMSSQLServer:
DescriptionOracleMSSQLServerModeldatabaseNomodeldatabaseNewlycreateddatabasesinheritcharacteristics(users,etc.)fromthespecialdatabasenamed"model".
--Fred
DifferencesinManagingDatabaseObjects
LastUpdated:6/6/1999
Appliesto:Oracle7.3+,MSSQLServer6.5+
Thefollowingtableshowssomedifferencesinhowdatabaseobjects(tables,views,storedprocedures,etc.)aremanagedinOracleandMSSQLServer:
DescriptionOracleMSSQLServerFullyqualifiedname[schema.]table
[schema.]view[[[server.][database].][owner].]table
[[[server.][database].][owner].]viewTemptablesPre8i:Temporarytablesmustbedeletedexplicitly
8i+:CREATEGLOBALTEMPORARYTABLE
#table--Anytablenamedstartingwithapoundsign(#)isautomaticallydeletedwhentheuserlogsoffortheprocedureends.
##table--Sameasabove,exceptthatthetableisaccessibletootherusers.Re-creatinganobjectCREATEORREPLACE...DROP...
CREATE...CreateviewbeforedependenttablesCREATEFORCEVIEWNotsupported.Tablesusedbyviewmustexistbeforeviewcanbecreated.
--Fred
DifferencesinManagingUsers
LastUpdated:6/6/1999
Appliesto:Oracle7.3+,MSSQLServer6.5+
ThefollowingtableshowssomedifferencesinhowusersaremanagedinOracleandMSSQLServer:
DescriptionOracleMSSQLServerMembershipingroupsEachusercanbeamemberofanynumberofgroups.Eachusercanbeamemberofonlyonegroupotherthan"public".
--Fred
DifferencesinIntegrationwithMSADO,RDO,etc.
LastUpdated:6/6/1999
Appliesto:Oracle7.3+,MSSQLServer6.5+
ThefollowingtableshowsthedifferenttechniquesusedinOracleandMSSQLServertointeractwithMSADO,RDO,etc.:
DescriptionOracleMSSQLServerReturnarecordsettothecallerReturnahandletoacursor.
Formoreinfo:SeeMSKBarticleQ174679.SELECTwithnoINTOclause;
MultiplesuchSELECTsreturnmultiplerecordsets
--Fred
MiscellaneousDifferences
LastUpdated:6/6/1999
Appliesto:Oracle7.3+,MSSQLServer6.5+
ThefollowingtableshowsmiscellaneousdifferencesbetweenOracleandMSSQLServer:
DescriptionOracleMSSQLServerGenerateuniquenumbersCREATESEQUENCEIDENTITYcolumnofatableCascadedDELETEDELETECASCADE...(usetriggers)Callauser-definedfunctionfromaSQLstatement(ascolumnofSELECTorexpressioninWHEREclause)supportednotsupported
--Fred
SeeAlso
LastUpdated:3/3/2001
Appliesto:Oracle7.3+,MSSQLServer6.5+
ThefollowingaregoodsourcesofinfoaboutdifferencesbetweenOracleandMSSQLServer:
Bowman,JudithS.,SandraL.Emerson,andMarcyDarnovsky.ThePracticalSQLHandbook.Addison-WesleyPublishingCompany,1993.ISBN0-201-62623-3.
ThisbookgivesagoodintroductiontoSQL,withaslightemphasisonSybase,butwithausefulsummaryinthebackofthesyntaxforeachoftheSQLstatements(SELECT,INSERT,UPDATE,DELETE,CREATE,DROP,GRANT,REVOKE,etc.)foreachofthemajordatabases(Oracle,Sybase,DB2,Informix,Ingres,etc.)Thebookpre-datesMSSQLServer,buttheSybaseinfoisagoodapproximationsinceMSSQLServerisaderivativeofSybase.
"MigratingOracleApplicationstoSQLServer"onMSDNCD,andatMSTechNetWebsite:
http://www.microsoft.com/TechNet/sql/Tools/Sqldevkt/ORCL2SQL.asp
Microsoftclearlyintendedthistobeusedinonedirectiononly,butIveuseditquitesuccessfullytotranslatemySQLServerknowledgetoOracleaswell.
最近由权威调查机构Evans数据公司进行的一项调查显示,MySQL在过去两年已经获得了25%的市场份额。该调查公司还预测,相比其他的开源数据库和闭源数据库。 |
|