Sie sind auf Seite 1von 13

How do you implement one-to-one, one-to-many and many-to-many relationships while designing tables?

One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign key relationships. One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key relationships. Many-to-Many relationships are implemented using a junction table with the keys from both the tables forming the composite primary key of the junction table. It will be a good idea to read up a database designing fundamentals te t book. !hat"s the difference between a primary key and a uni#ue key? $oth primary key and uni#ue enforce uni#ueness of the column on which they are defined. $ut by default primary key creates a clustered inde on the column, where are uni#ue creates a nonclustered inde by default. %nother major difference is that, primary key doesn"t allow &'((s, but uni#ue key allows one &'(( only. !hat are user defined datatypes and when you should go for them? 'ser defined datatypes let you e tend the base )*( )er+er datatypes by pro+iding a descripti+e name, and format to the database. ,ake for e ample, in your database, there is a column called -light.&um which appears in many tables. In all these tables it should be +archar/01. In this case you could create a user defined datatype called -light.num.type of +archar/01 and use it across all your tables. )ee sp.addtype, sp.droptype in books online. !hat is bit datatype and what"s the information that can be stored inside a bit column? $it datatype is used to store boolean information like 2 or 3 /true or false1. 'ntill )*( )er+er 4.5 bit datatype could hold either a 2 or 3 and there was no support for &'((. $ut from )*( )er+er 6.3 onwards, bit datatype can represent a third state, which is &'((. 7efine candidate key, alternate key, composite key. % candidate key is one that can identify each row of a table uni#uely. 8enerally a candidate key becomes the primary key of the table. If the table has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys. % key formed by combining at least two or more columns is called composite key. !hat are defaults? Is there a column to which a default can"t be bound? % default is a +alue that will be used by a column, if no +alue is supplied to that column while inserting data. I79&,I,: columns and timestamp columns can"t ha+e defaults bound to them. )ee ;<9%,9 79-'%(, in books online.

!hat is a transaction and what are %;I7 properties? % transaction is a logical unit of work in which, all the steps must be performed or none. %;I7 stands for %tomicity, ;onsistency, Isolation, 7urability. ,hese are the properties of a transaction. -or more information and e planation of these properties, see )*( )er+er books online or any <7$M) fundamentals te t book. 9 plain different isolation le+els %n isolation le+el determines the degree of isolation of data between concurrent transactions. ,he default )*( )er+er isolation le+el is <ead ;ommitted. Here are the other isolation le+els /in the ascending order of isolation1= <ead 'ncommitted, <ead ;ommitted, <epeatable <ead, )eriali>able. )ee )*( )er+er books online for an e planation of the isolation le+els. $e sure to read about )9, ,<%&)%;,IO& I)O(%,IO& (9?9(, which lets you customi>e the isolation le+el at the connection le+el.

;<9%,9 I&79@ myInde O& my,able/my;olumn1 !hat type of Inde will get created after e ecuting the abo+e statement? &on-clustered inde . Important thing to note= $y default a clustered inde gets created on the primary key, unless specified otherwise. !hat"s the ma imum si>e of a row? 0343 bytes. 7on"t be surprised with #uestions like "what is the ma imum number of columns per table". ;heck out )*( )er+er books online for the page titled= AMa imum ;apacity )pecificationsA. 9 plain %cti+eB%cti+e and %cti+eBCassi+e cluster configurations Hopefully you ha+e e perience setting up cluster ser+ers. $ut if you don"t, at least be familiar with the way clustering works and the two clusterning configurations %cti+eB%cti+e and %cti+eBCassi+e. )*( )er+er books online has enough information on this topic and there is a good white paper a+ailable on Microsoft site. 9 plain the architecture of )*( )er+er ,his is a +ery important #uestion and you better be able to answer it if consider yourself a 7$%. )*( )er+er books online is the best place to read about )*( )er+er architecture. <ead up the chapter dedicated to )*( )er+er %rchitecture. !hat is lock escalation? (ock escalation is the process of con+erting a lot of low le+el locks /like row locks, page locks1 into higher le+el locks /like table locks1. 9+ery lock is a memory structure too many locks would mean, more memory being occupied by locks. ,o pre+ent this from happening, )*( )er+er escalates the many fine-grain locks to fewer coarse-grain locks. (ock escalation threshold was definable in )*( )er+er 4.5, but from )*( )er+er 6.3 onwards it"s dynamically managed by )*( )er+er.

!hat"s the difference between 79(9,9 ,%$(9 and ,<'&;%,9 ,%$(9 commands? 79(9,9 ,%$(9 is a logged operation, so the deletion of each row gets logged in the transaction log, which makes it slow. ,<'&;%,9 ,%$(9 also deletes all the rows in a table, but it won"t log the deletion of each row, instead it logs the deallocation of the data pages of the table, which makes it faster. Of course, ,<'&;%,9 ,%$(9 can be rolled back. 9 plain the storage models of O(%C ;heck out MO(%C, <O(%C and HO(%C in )*( )er+er books online for more infomation. !hat are the new features introduced in )*( )er+er D333 /or the latest release of )*( )er+er at the time of your inter+iew1? !hat changed between the pre+ious +ersion of )*( )er+er and the current +ersion? ,his #uestion is generally asked to see how current is your knowledge. 8enerally there is a section in the beginning of the books online titled A!hat"s &ewA, which has all such information. Of course, reading just that is not enough, you should ha+e tried those things to better answer the #uestions. %lso check out the section titled A$ackward ;ompatibilityA in books online which talks about the changes that ha+e taken place in the new +ersion. !hat are constraints? 9 plain different types of constraints. ;onstraints enable the <7$M) enforce the integrity of the database automatically, without needing you to create triggers, rule or defaults. ,ypes of constraints= &O, &'((, ;H9;E, '&I*'9, C<IM%<: E9:, -O<9I8& E9:

-or an e planation of these constraints see books online for the pages titled= A;onstraintsA and A;<9%,9 ,%$(9A, A%(,9< ,%$(9A !har is an inde ? !hat are the types of inde es? How many clustered inde es can be created on a table? I create a separate inde on each column of a table. what are the ad+antages and disad+antages of this approach? Inde es in )*( )er+er are similar to the inde es in books. ,hey help )*( )er+er retrie+e the data #uicker. Inde es are of two types. ;lustered inde es and non-clustered inde es. !hen you craete a clustered inde on a table, all the rows in the table are stored in the order of the clustered inde key. )o, there can be only one clustered inde per table. &on-clustered inde es ha+e their own storage separate from the table data storage. &on-clustered inde es are stored as $-tree structures /so do clustered inde es1, with the leaf le+el nodes ha+ing the inde key and it"s row locater. ,he row located could be the <I7 or the ;lustered inde key, depending up on the absence or presence of clustered inde on the table. If you create an inde on each column of a table, it impro+es the #uery performance, as the #uery optimi>er can choose from all the e isting inde es to come up with an efficient e ecution plan. %t the same t ime, data modification operations /such as I&)9<,, 'C7%,9, 79(9,91 will become slow, as e+ery time data changes in the table, all the inde es need to be updated. %nother disad+antage is that, inde es need disk space, the more inde es you ha+e, more disk space is used. $ack to top 7atabase administration !hat is <%I7 and what are different types of <%I7 configurations? <%I7 stands for <edundant %rray of Ine pensi+e 7isks, used to pro+ide fault tolerance to database ser+ers. ,here are si <%I7 le+els 3 through 5 offering different le+els of performance, fault tolerance. M)7& has some information about <%I7 le+els and for detailed information, check out the <%I7 ad+isory board"s homepage !hat are the steps you will take to impro+e performance of a poor performing #uery? ,his is a +ery open ended #uestion and there could be a lot of reasons behind the poor performance of a #uery. $ut some general issues that you could talk about would be= &o inde es, table scans, missing or out of date statistics, blocking, e cess recompilations of stored procedures, procedures and triggers without )9, &O;O'&, O&, poorly written #uery with unnecessarily complicated joins, too much normali>ation, e cess usage of cursors and temporary tables. )ome of the toolsBways that help you troubleshooting performance problems are= )9, )HO!C(%&.%(( O&, )9, )HO!C(%&.,9@, O&, )9, ),%,I),I;) IO O&, )*( )er+er Crofiler, !indows &, BD333 Cerformance monitor, 8raphical e ecution plan in *uery %naly>er. 7ownload the white paper on performance tuning )*( )er+er from Microsoft web site. 7on"t forget to check out s#l-ser+erperformance.com !hat are the steps you will take, if you are tasked with securing an )*( )er+er? %gain this is another open ended #uestion. Here are some things you could talk about= Creferring &, authentication, using ser+er, databse and application roles to control access to the data, securing the physical database files using &,-) permissions, using an unguessable )% password, restricting physical access to the )*( )er+er, renaming the %dministrator account on the )*( )er+er computer, disabling the 8uest account, enabling auditing, using multiprotocol encryption, setting up ))(, setting up firewalls, isolating )*( )er+er from the web ser+er etc. <ead the white paper on )*( )er+er security from Microsoft website. %lso check out My )*( )er+er security best practices !hat is a deadlock and what is a li+e lock? How will you go about resol+ing deadlocks? 7eadlock is a situation when two processes, each ha+ing a lock on one piece of data, attempt to ac#uire a lock on the other"s piece. 9ach process would wait indefinitely for the other to release the lock, unless one of the user processes is terminated. )*( )er+er detects deadlocks and terminates one user"s process.
/top1

% li+elock is one, where a re#uest for an e clusi+e lock is repeatedly denied because a series of o+erlapping shared locks keeps interfering. )*( )er+er detects the situation after four denials and refuses further shared locks. % li+elock also occurs when read transactions monopoli>e a table or page, forcing a write transaction to wait indefinitely. ;heck out )9, 79%7(O;E.C<IO<I,: and AMinimi>ing 7eadlocksA in )*( )er+er books online. %lso check out the article *24FF43 from Microsoft knowledge base. !hat is blocking and how would you troubleshoot it? $locking happens when one connection from an application holds a lock and a second connection re#uires a conflicting lock type. ,his forces the second connection to wait, blocked on the first. <ead up the following topics in )*( )er+er books online= 'nderstanding and a+oiding blocking, ;oding efficient transactions. 9 plain ;<9%,9 7%,%$%)9 synta Many of us are used to craeting databases from the 9nterprise Manager or by just issuing the command= ;<9%,9 7%,%$%9 My7$. $ut what if you ha+e to create a database with two filegroups, one on dri+e ; and the other on dri+e 7 with log on dri+e 9 with an initial si>e of 433 M$ and with a growth factor of 25G? ,hat"s why being a 7$% you should be familiar with the ;<9%,9 7%,%$%)9 synta . ;heck out )*( )er+er books online for more information. How to restart )*( )er+er in single user mode? How to start )*( )er+er in minimal configuration mode? )*( )er+er can be started from command line, using the )*()9<?<.9@9. ,his 9@9 has some +ery important parameters with which a 7$% should be familiar with. -m is used for starting )*( )er+er in single user mode and -f is used to start the )*( )er+er in minimal confuguration mode. ;heck out )*( )er+er books online for more parameters and their e planations. %s a part of your job, what are the 7$;; commands that you commonly use for database maintenance? 7$;; ;H9;E7$, 7$;; ;H9;E,%$(9, 7$;; ;H9;E;%,%(O8, 7$;; ;H9;E%((O;, 7$;; )HO!;O&,I8, 7$;; )H<I&E7%,%$%)9, 7$;; )H<I&E-I(9 etc. $ut there are a whole load of 7$;; commands which are +ery useful for 7$%s. ;heck out )*( )er+er books online for more information. !hat are statistics, under what circumstances they go out of date, how do you update them? )tatistics determine the selecti+ity of the inde es. If an inde ed column has uni#ue +alues then the selecti+ity of that inde is more, as opposed to an inde with non-uni#ue +alues. *uery optimi>er uses these inde es in determining whether to choose an inde or not while e ecuting a #uery. )ome situations under which you should update statistics= 21 If there is significant change in the key +alues in the inde D1 If a large amount of data in an inde ed column has been added, changed, or remo+ed /that is, if the distribution of key +alues has changed1, or the table has been truncated using the ,<'&;%,9 ,%$(9 statement and then repopulated H1 7atabase is upgraded from a pre+ious +ersion (ook up )*( )er+er books online for the following commands= 'C7%,9 ),%,I),I;), ),%,).7%,9, 7$;; )HO!.),%,I),I;), ;<9%,9 ),%,I),I;), 7<OC ),%,I),I;), sp.autostats, sp.createstats, sp.updatestats !hat are the different ways of mo+ing dataBdatabases between ser+ers and databases in )*( )er+er? ,here are lots of options a+ailable, you ha+e to choose your option depending upon your re#uirements. )ome of the options you ha+e are= $%;E'CB<9),O<9, dettaching and attaching databases, replication, 7,), $;C, logshipping, I&)9<,...)9(9;,, )9(9;,...I&,O, creating I&)9<, scripts to generate data. 9 plian different types of $%;E'Cs a+aialabe in )*( )er+er? 8i+en a particular scenario, how would you go about choosing a backup plan?

,ypes of backups you can create in )*( )e+er 6.3I are -ull database backup, differential database backup, transaction log backup, filegroup backup. ;heck out the $%;E'C and <9),O<9 commands in )*( )er+er books online. $e prepared to write the commands in your inter+iew. $ooks online also has information on detailed backupBrestore architecture and when one should go for a particular kind of backup. !hat is database replicaion? !hat are the different types of replication you can set up in )*( )er+er? <eplication is the process of copyingBmo+ing data between databases on the same or different ser+ers. )*( )er+er supports the following types of replication scenarios= )napshot replication ,ransactional replication /with immediate updating subscribers, with #ueued updating subscribers1 Merge replication

)ee )*( )er+er books online for indepth co+erage on replication. $e prepared to e plain how different replication agents function, what are the main system tables used in replication etc. How to determine the ser+ice pack currently installed on )*( )er+er? ,he global +ariable JJ?ersion stores the build number of the s#lser+r.e e, which is used to determine the ser+ice pack installed. ,o know more about this process +isit )*( )er+er ser+ice packs and +ersions. $ack to top 7atabase programming
/top1

!hat are cursors? 9 plain different types of cursors. !hat are the disad+antages of cursors? How can you a+oid cursors? ;ursors allow row-by-row prcessing of the resultsets. ,ypes of cursors= )tatic, 7ynamic, -orward-only, Eeyset-dri+en. )ee books online for more information. 7isad+antages of cursors= 9ach time you fetch a row from the cursor, it results in a network roundtrip, where as a normal )9(9;, #uery makes only one rowundtrip, howe+er large the resultset is. ;ursors are also costly because they re#uire more resources and temporary storage /results in more IO operations1. -urthere, there are restrictions on the )9(9;, statements that can be used with some types of cursors. Most of the times, set based operations can be used instead of cursors. Here is an e ample= If you ha+e to gi+e a flat hike to your employees using the following criteria= )alary between H3333 and K3333 -- 5333 hike )alary between K3333 and 55333 -- 6333 hike )alary between 55333 and 45333 -- F333 hike In this situation many de+elopers tend to use a cursor, determine each employee"s salary and update his salary according to the abo+e formula. $ut the same can be achie+ed by multiple update statements or can be combined in a single 'C7%,9 statement as shown below= UPDATE tbl_emp SET salary = CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000 WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000 WHEN salary BETWEEN 55000 AND 5000 THEN salary + !0000 END %nother situation in which de+elopers tend to use cursors= :ou need to call a stored procedure when a column in a particular row meets certain condition. :ou don"t ha+e to use cursors for this. ,his can be achie+ed using !HI(9 loop, as long as there is a uni#ue key to identify each row. -or e amples of using !HI(9 loop for row by row processing, check out the "My code library" section of my site or search for !HI(9.

!rite down the general synta for a )9(9;, statements co+ering all the options. Here"s the basic synta = /%lso checkout )9(9;, in books online for ad+anced synta 1. )9(9;, select.list LI&,O new.table.M -<OM table.source L!H9<9 search.conditionM L8<O'C $: group.by.e pressionM LH%?I&8 search.conditionM LO<79< $: order.e pression L%); N 79);M M !hat is a join and e plain different types of joins. Ooins are used in #ueries to e plain how different tables are related. Ooins also let you select data from a table depending upon data from another table. ,ypes of joins= I&&9< OOI&s, O',9< OOI&s, ;<O)) OOI&s. O',9< OOI&s are further classified as (9-, O',9< OOI&), <I8H, O',9< OOI&) and -'(( O',9< OOI&). -or more information see pages from books online titled= AOoin -undamentalsA and A'sing OoinsA. ;an you ha+e a nested transaction? :es, +ery much. ;heck out $98I& ,<%&, ;OMMI,, <O(($%;E, )%?9 ,<%& and JJ,<%&;O'&, !hat is an e tended stored procedure? ;an you instantiate a ;OM object by using ,-)*(? %n e tended stored procedure is a function within a 7(( /written in a programming language like ;, ;II using Open 7ata )er+ices /O7)1 %CI1 that can be called from ,-)*(, just the way we call normal stored procedures using the 9@9; statement. )ee books online to learn how to create e tended stored procedures and how to add them to )*( )er+er. :es, you can instantiate a ;OM /written in languages like ?$, ?;II1 object from ,-)*( by using sp.O%;reate stored procedure. %lso see books online for sp.O%Method, sp.O%8etCroperty, sp.O%)etCroperty, sp.O%7estroy. -or an e ample of creating a ;OM object in ?$ and calling it from ,-)*(, see "My code library" section of this site. !hat is the system function to get the current user"s user id? ')9<.I7/1. %lso check out other system functions like ')9<.&%M9/1, ):),9M.')9<, )9))IO&.')9<, ;'<<9&,.')9<, ')9<, )')9<.)I7/1, HO),.&%M9/1. !hat are triggers? How many triggers you can ha+e on a table? How to in+oke a trigger on demand? ,riggers are special kind of stored procedures that get e ecuted automatically when an I&)9<,, 'C7%,9 or 79(9,9 operation takes place on a table. In )*( )er+er 4.5 you could define only H triggers per table, one for I&)9<,, one for 'C7%,9 and one for 79(9,9. -rom )*( )er+er 6.3 onwards, this restriction is gone, and you could create multiple triggers per each action. $ut in 6.3 there"s no way to control the order in which the triggers fire. In )*( )er+er D333 you could specify which trigger fires first or fires last using sp.settriggerorder ,riggers can"t be in+oked on demand. ,hey get triggered only when an associated action /I&)9<,, 'C7%,9, 79(9,91 happens on the table on which they are defined. ,riggers are generally used to implement business rules, auditing. ,riggers can also be used to e tend the referential integrity checks, but where+er possible, use constraints for this purpose, instead of triggers, as constraints are much faster. ,ill )*( )er+er 6.3, triggers fire only after the data modification operation happens. )o in a way, they are called post triggers. $ut in )*( )er+er D333 you could create pre triggers also. )earch )*( )er+er D333 books online for I&),9%7 O- triggers.

%lso check out books online for "inserted table", "deleted table" and ;O('M&).'C7%,97/1 ,here is a trigger defined for I&)9<, operations on a table, in an O(,C system. ,he trigger is written to instantiate a ;OM object and pass the newly insterted rows to it for some custom processing. !hat do you think of this implementation? ;an this be implemented better? Instantiating ;OM objects is a time consuming process and since you are doing it from within a trigger, it slows down the data insertion process. )ame is the case with sending emails from triggers. ,his scenario can be better implemented by logging all the necessary data into a separate table, and ha+e a job which periodically checks this table and does the needful. !hat is a self join? 9 plain it with an e ample. )elf join is just like any other join, e cept that two instances of the same table will be joined in the #uery. Here is an e ample= 9mployees table which contains rows for normal employees as well as managers. )o, to find out the managers of all the employees, you need a self join. C"EATE TAB#E emp $ emp%& %'t( m)r%& %'t( emp'ame *+ar$!0, , -NSE"T -NSE"T -NSE"T -NSE"T -NSE"T emp emp emp emp emp SE#ECT SE#ECT SE#ECT SE#ECT SE#ECT !(.(/0yas/ .(3(/12+a'/ 3(NU##(/S+2b+a/ 4(.(/S+r%&+ar/ 5(.(/S23rab+/

SE#ECT t!4emp'ame 5Empl2yee6( t.4emp'ame 51a'a)er6 7"81 emp t!( emp t. WHE"E t!4m)r%& = t.4emp%& Here"s an ad+anced #uery using a (9-, O',9< OOI& that e+en returns the employees without managers /super bosses1 SE#ECT t!4emp'ame 5Empl2yee6( C8A#ESCE$t.4emp'ame( /N2 ma'a)er/, 51a'a)er6 7"81 emp t! #E7T 8UTE" 98-N emp t. 8N t!4m)r%& = t.4emp%& 8i+en an employee table, how would you find out the second highest salary?

!hy are my insert, update statements failing with the following error? )er+er= Msg 025D, (e+el 24, )tate F, (ine 2 )tring or binary data would be truncated. ,he statement has been terminated. !hat is the ,-)*( e#ui+alent of II- /immediate ifBternary operator1 function of other programming languages? How to programmatically find out when the )*( )er+er ser+ice started? How to get rid of the time part from the date returned by 89,7%,9 function?

How to upload images or binary files into )*( )er+er tables? How to run an )*( script file that is located on the disk, using ,-)*(? How to get the complete error message from ,-)*( while error handling? How to get the first day of the week, last day of the week and last day of the month using ,-)*( date functions? How to pass a table name, column name etc. to the stored procedure so that I can dynamically select from a table? 9rror inside a stored procedure is not being raised to my front-end applications using %7O. $ut I get the error when I run the procedure from *uery %naly>er How to suppress error messages in stored proceduresBtriggers etc. using ,-)*(? How to sa+e the output of a #ueryBstored procedure to a te t file? How to join tables from different databases? How to join tables from different ser+ers? How to con+ert timestamp data to date data /datetime datatype1? ;an I in+okeBinstantiate ;OM objects from within stored procedures or triggers using ,-)*(? Oracle has a rownum to access rows of a table using row number or row id. Is there any e#ui+alent for that in )*( )er+er? Or how to generate output with row number in )*( )er+er? How to specify a network library like ,;CBIC using %7O connect string? How to generate scripts for repetiti+e tasks like truncating all the tables in a database, changing owner of all the database objects, disabling constraints on all tables etc? Is there a way to find out when a stored procedure was last updated? How to find out all the I79&,I,: columns of all the tables in a gi+en database? How to search the code of stored procedures? How to retrie+e the generated 8'I7 +alue of a newly inserted row? Is there an JJ8'I7, just like JJI79&,I,: ? !hy are my insert, update statements failing with the following error? )er+er= Msg 025D, (e+el 24, )tate F, (ine 2 )tring or binary data would be truncated. ,he statement has been terminated. PtopQ ,his error occurs, when the length of the +alue entered by you into a char, +archar, nchar, n+archar column is longer than the ma imum length of the column. -or e ample, inserting "-%*" into a char/D1 column would result in this error. Crofiler is handy in troubleshooting this error. If data truncation is okay with you and you don"t want to see this error, then turn off %&)I !%<&I&8) by using the following )9, command= SET ANS-_WA"N-N:S 877. )teps to reproduce the problem= C"EATE TAB#E 1yTable $ P;ey %'t P"-1A"< =E<( C2l! *+ar$!0, , :8 -NSE"T -NT8 1yTable $P;ey( C2l!, 0A#UES $!( /S># Ser?er Cl3ster%') 7A>/,

:8 Make sure, you restrict the length of input, in your front-end applications. -or e ample, you could use the M%@(9&8,H property of the te t bo es in H,M( forms. 9.g= @-NPUT NA1E = ANameA T<PE= TEBTB8B 1AB#EN:TH=.0C !hat is the ,-)*( e#ui+alent of II- /immediate ifBternary operator1 function of other programming languages? PtopQ ;%)9 is the e#ui+alent of II- function. )ee )*( )er+er $ooks Online for more information. Here"s a #uick e ample= C"EATE TAB#E Pe2ple $ 5-D6 %'t P"-1A"< =E<( 5Name6 ?ar*+ar$.5, N8T NU##( SeD b%t NU## , -NSE"T -NT8 Pe2ple $5-D6(5Name6( SeD, 0A#UES $!(/92+' Dy;es/( !, -NSE"T -NT8 Pe2ple $5-D6(5Name6( SeD, 0A#UES $.(/Deb2ra+ Cr22;/( 0, -NSE"T -NT8 Pe2ple $5-D6(5Name6( SeD, 0A#UES $3(/P S S3brama'yam/( NU##, SE#ECT 5-D6( 5Name6( CASE SeD WHEN ! THEN /1ale/ WHEN 0 THEN /7emale/ E#SE /N2t spe*%E%e&/ END AS SeD 7"81 Pe2ple How to programmatically find out when the )*( )er+er ser+ice started? PtopQ 9+erytime )*( )er+er starts, it recreates the tempdb database. )o, the creation date and time of the tempdb database tells us the date and time at which )*( )er+er ser+ice started. ,his information is stored in the crdate column of the sysdatabases table in master database. Here"s the #uery to find that out= SE#ECT *r&ate AS /S># Ser?er ser?%*e starte& appr2D%mately atF/ 7"81 master4&b24sys&atabases WHE"E 'ame = /temp&b/ )*( )er+er error log also has this information /,his is more accurate1 and the error log can be #ueried using p.readerrorlog How to get rid of the time part from the date returned by 89,7%,9 function? PtopQ !e ha+e to use the ;O&?9<, function to strip the time off the date. %ny of the following commands will do this= SE#ECT SE#ECT SE#ECT SE#ECT C8N0E"T$*+ar(:ETDATE$,(!0!, C8N0E"T$*+ar(:ETDATE$,(!0., C8N0E"T$*+ar(:ETDATE$,(!03, C8N0E"T$*+ar(:ETDATE$,(!,

)ee )*( )er+er $ooks Online for more information on ;O&?9<, function. How to upload images or binary files into )*( )er+er tables? PtopQ -irst of all, if possible, try not to stored images and other binary files in the )*( )er+er tables, as they slow things down. Instead, store a link /file path1 to the file in the tables and let your applications directly access the files. $ut if you must store these files within )*( )er+er, use the te tBnte t or image datatype columns and consider the following options=

)*( )er+er 6.3 and D333 come with a utility called te tcopy.e e. :ou can locate this file in the $inn folder under your )*( )er+er installation folder. <un this file from command prompt, and it will prompt you for re#uired input 'se the 8et;hunk and %ppend;hunk methods of %7O -ield object. M)7& has e amples 'se the %7O )tream object 'se the $ulk Insert Image utility /$II1 that ships with )*( )er+er D333 /;an be found at RCrogram -ilesRMicrosoft )*( )er+erR03R,oolsR7e+toolsR)amplesR'tils1

How to run an )*( script file that is located on the disk, using ,-)*(? PtopQ ,here"s no direct command to read a script file and e ecute it. $ut the is#l.e e and os#l.e e come in handy when you ha+e to e ecute a script file from within ,-)*(. Oust call any of these e es using p.cmdshell and pass the script file name as parameter to it. )ee )*( )er+er $ooks Online for more information about the input parameters of these e es. Here are some #uick e amples= EBEC master44Dp_*m&s+ell /2sGl HS?a%2 HUsa HPIaass&s! H%*FJ1yS>l4sGl H'/ EBEC master44Dp_*m&s+ell /%sGl HS?a%2 HUsa HPIaass&s! H%*FJ1yS>l4sGl H'/ )ee p.cmdshell in )*( )er+er $ooks Online if you are ha+ing permissions problems in getting this techni#ue to work. How to get the complete error message from ,-)*( while error handling? PtopQ 'nfortunately, the error handling capabilities of )*( )er+er are limited. !hen an error occurs, all you can get is the error number, using the JJ9<<O< global +ariable. ,here is no JJ9<<O<.M9))%89 global +ariable to get the error description. -or a complete error message, you can always #uery the master..sysmessages table using the error number, but most of these messages ha+e place holders /like Gs, Gl etc.1, and hence we can"t get the complete error message. Howe+er, the client applications using an object model such as <7O, %7O ha+e access to the complete error message. How to get the first day of the week, last day of the week and last day of the month using ,-)*( date functions? PtopQ Here"s the code= DEC#A"E KDate &atet%me SET KDate = /.00!L0ML3!/ SE#ECT DATEADD$&&(H$DATEPA"T$&N( KDate, H !,(KDate, AS /7%rst &ay 2E t+e Nee;/ SE#ECT DATEADD$&&(H$DATEPA"T$&N( KDate, H 7,(KDate, AS /#ast &ay 2E t+e Nee;/ SE#ECT DA<$DATEADD$&( HDA<$DATEADD$m(!(KDate,,(DATEADD$m(!(KDate,,, AS /#ast &ay 2E t+e m2't+/ How to pass a table name, column name etc. to the stored procedure so that I can dynamically select from a table? PtopQ $asically, )9(9;, and other commands like 7<OC ,%$(9 won"t let you use a +ariable instead of a hardcoded table name. ,o o+ercome this problem, you ha+e to use dynamic s#l. $ut dynamic )*( has some disad+antages. It"s slow, as the dynamic )*( statement needs to be parsed e+erytime it"s e ecuted. -urther, the user who is e ecuting the dynamic )*( string needs direct permissions on the tables, which defeats the purpose of ha+ing stored procedures to mask the underlying tables. Ha+ing said that, here are some e amples of dynamic )*(= /%lso see sp.e ecutes#l in )*( )er+er $ooks Online1 C"EATE P"8C Dr2pTable KTable sys'ame AS EBEC $/D"8P TAB#E / + KTable, :8 EBEC Dr2pTable /1yTable/ :8 C"EATE P"8C Sele*tTable KTable sys'ame AS

EBEC $/SE#ECT O 7"81 / + KTable, :8 EBEC Sele*tTable /1yTable/ -or a complete discussion on the pros and cons of dynamic )*( check out 9rland"s article= ,he curse and blessings of dynamic )*( 9rror inside a stored procedure is not being raised to my front-end applications using %7O. $ut I get the error when I run the procedure from *uery %naly>er PtopQ ,his typically happens when your stored procedure is returning multiple resultsets and the offending )*( statement is e ecuted after returning one or more resultsets. %7O will not return an error untill it processes all the recordsets returned before the offending )*( statement got e ecuted. )o, to get to the error message returned by your procedure. :ou ha+e to loop through all the recordsets returned. %7O <ecordset object has a method called &e t<ecordset, which lets you loop through the recordsets. Ha+ing )9, &O;O'&, O& at the beginning of the procedure also helps a+oid this problem. )9, &O;O'&, O& also helps in impro+ing the stored procedure performance. Here"s a sample procedure to simulate the problem= C"EATE P"8C TestPr2* AS SE#ECT 1AB$C2l!, 7"81 TestTable SE#ECT 1-N$C2l!, 7"81 TestTable -NSE"T -NT8 TestTable $C2l!( C2l., 0A#UES $!(/8ra*le a'& S># Ser?er *2mpar%s2'/, -NSE"T -NT8 TestTable $C2l!( C2l., 0A#UES $!(/H2N t2 *2'E%)3re S># Ser?erP/, HH D3ppl%*ate ;ey err2r 2**3rs :8 How to suppress error messages in stored proceduresBtriggers etc. using ,-)*(? PtopQ It"s not possible to suppress error messages from within ,-)*(. 9rror messages are always returned to the client. If you don"t want your users to see these raw error messages, you should handle them in your front-end applications. -or e ample, if you are using %7O from %)C to connect to )*( )er+er, you would do something like the following= 8' Err2r "es3me NeDt Set "s = C2''4EDe*3te $A-NSE"T -NT8 1yTable $!(/H2N t2 m%)rate Er2m 8ra*le t2 S># Ser?er/(/B22;/A, -E Err4N3mber @C 0 T+e' "esp2'se4Wr%te $AErr2r 2**3rre& N+%le %'sert%') 'eN &ataA, 8' Err2r :2T2 0 How to sa+e the output of a #ueryBstored procedure to a te t file using ,-)*(? PtopQ ,-)*( by itself has no support for sa+ing the output of #ueriesBstored procedures to te t files. $ut you could achie+e this using the command line utilities like is#l.e e and os#l.e e. :ou could either in+oke these e e files directly from command promptBbatch files or from ,-)*( using the p.cmdshell command. Here are the e amples= -rom command prompt= 2sGl4eDe HS <23rSer?erName HU sa HP se*ret*2&e H> AEBEC sp_N+2.A H2 AEFJ23tp3t4tDtA -rom ,-)*(= EBEC master44Dp_*m&s+ell /2sGl4eDe HS <23rSer?erName HU sa HP se*ret*2&e H> AEBEC sp_N+2.A H2 AEFJ23tp3t4tDtA/ *uery %naly>er lets you sa+e the #uery output to te t files manually. ,he output of stored procedures that are run as a part of a scheduled job, can also be sa+ed to a te t file. $;C and 7ata ,ransformation )er+ices /7,)1 let you e port table data to te t files. How to join tables from different databases? PtopQ

:ou just ha+e to #ualify the table names in your SE#ECT #ueries with database name, followed by table owner name. In the following e ample, ,able2 from pubs database and ,ableD from northwind database are being joined on the column i. $oth tables are owned by dbo. SE#ECT a4%( a4Q 7"81 p3bs4&b24Table! a -NNE" 98-N '2rt+N%'&4&b24Table. b 8N a4% = b4% :8 How to join tables from different ser+ers? PtopQ ,o be able to join tables between two )*( )er+ers, first you ha+e to link them. %fter the linked ser+ers are setup, you just ha+e to prefi your tables names with ser+er name, database name, table owner name in your )9(9;, #ueries. ,he following e ample links )9<?9<.32 to )9<?9<.3D. 9 ecute the following commands in )9<?9<.3D= EBEC sp_a&&l%';e&ser?er SE"0E"_0! :8 LO T+e E2ll2N%') *2mma'& l%';s /sa/ l2)%' 2' SE"0E"_0. N%t+ t+e /sa/ l2)%' 2E SE"0E"_0! OL EBEC sp_a&&l%';e&sr?l2)%' Krmtsr?'ame = /SE"0E"_0!/( K3seselE = /Ealse/( Kl2*all2)%' = /sa/( Krmt3ser = /sa/( KrmtpassN2r& = /sa passN2r& 2E SE"0E"_0!/ :8 SE#ECT a4t%tle_%& 7"81 SE"0E"_0!4p3bs4&b24t%tles a -NNE" 98-N SE"0E"_0.4p3bs4&b24t%tles b 8N a4t%tle_%& = b4t%tle_%& :8 How to con+ert timestamp data to date data /datetime datatype1? PtopQ ,he name timestamp is a little misleading. ,imestamp data has nothing to do with dates and times and can not be con+erted to date data. % timestamp is a uni#ue number within the database and is e#ui+alent to a binary/01B+arbinary/01 datatype. % table can ha+e only one timestamp column. ,imestamp +alue of a row changes with e+ery update of the row. ,o a+oid the confusion, )*( )er+er D333 introduced a synonym to timestamp, called row+ersion. ;an I in+okeBinstantiate ;OM objects from within stored procedures or triggers using ,-)*(? PtopQ :es. )*( )er+er pro+ides system stored procedures that let you instantiate ;OM objects using ,-)*( from stored procedures, triggers and )*( batches. )earch )*( )er+er $ooks Online for sp_8ACreate and sp.O%S for documentation and e amples. %lso check out my code library for an e ample. Oracle has a rownum to access rows of a table using row number or row id. Is there any e#ui+alent for that in )*( )er+er? Or how to generate output with row number in )*( )er+er? PtopQ ,here is no direct e#ui+alent to Oracle"s rownum or row id in )*( )er+er. )trictly speaking, in a relational database, rows within a table are not ordered and a row id won"t really make sense. $ut if you need that functionality, consider the following three alternati+es= %dd an I79&,I,: column to your table. )ee $ooks Online for more information 'se the following #uery to generate a row number for each row. ,he following #uery generates a row number for each row in the authors table of pubs database. -or this #uery to work, the table must ha+e a uni#ue key. SE#ECT $SE#ECT C8UNT$%4a3_%&,7"81 p3bs44a3t+2rs % WHE"E %4a3_%& C= 24a3_%& , AS "2N-D( a3_E'ame + / / + a3_l'ame AS /A3t+2r 'ame/

7"81 p3bs44a3t+2rs 2 8"DE" B< "2N-D 'se a temporary table approach, to store the entire resultset into a temporary table, along with a row id generated by the I79&,I,:/1 function. ;reating a temporary table will be costly, especially when you are working with large tables. 8o for this approach, if you don"t ha+e a uni#ue key in your table. )earch for I79&,I,: /-unction1 in )*( )er+er $ooks Online.

-or more ideas on this topic, click here to read an informati+e article from Microsoft Enowledgebase. How to specify a network library like ,;CBIC using %7O connect string? PtopQ ,o specify ,;CBIC net library, append the following to your %7O connect string= &etworkTdbmssocn -or more information on specifying other net libraries in %7O connect strings, click here to read the article from Microsoft Enowledgebase. Is there a way to find out when a stored procedure was last updated? PtopQ )imple answer is "&o". ,he crdate column in the sysobjects table always contains the stored procedure create date, not the last updated date. :ou can use Crofiler to trace %(,9< C<O; calls to the database, but you can"t really afford to run a trace for e+er, as it"s resource intensi+e. Here is a simple ideaU !hene+er you ha+e to alter your stored procedure, first drop it, then recreate it with the updated code. ,his resets the crdate column of sysobjects table. If you can make sure your de+elopers always follow this plan, then the crdate column of sysobjects will always reflect the last updated date of the stored procedure. -or e ample, if I ha+e to modify a procedure named MyCroc, instead of doing A%(,9< C<O; MyCrocA, here"s what I would do= - 'se sp.helpte t to get the current code of MyCroc. - ;hange the code as needed. - <un the following code to drop the e isting +ersion of MyCroc=
-7 EB-STS$SE#ECT ! 7"81 sys2bQe*ts WHE"E 'ame = /1yPr2*/ AND type = /P/ AND USE"_NA1E$3%&, = /&b2/, BE:-N D"8P P"8C &b241yPr2* END

- <un the updated code to recreate MyCroc ,here is a much more powerful way out, if you can use ?isual )ource )afe /?))1. ?)) is a +ersion control software, that lets you manage your code. !ith ?)) in place, you will ha+e to maintain all your object creation scripts as script files and check them into ?)). !hen you ha+e to modify a particular stored procedure, check out that script from ?)), modify it, test it, create the stored procedure, and check the script back into ?)). ?)) can show you when a script got modified, by who and a whole lot of other information. %d+antages of using ?)) - :ou can +ersion control your software, as ?)) maintains all your changes as different +ersions - :ou can go back to a pre+ious known good +ersion of your stored procedure, if a de+eloper makes a mistake - 'sing the labelling feature, you can re+ert back to an entire set of scripts at a particular point in time - :ou can control access to your source code by configuring permissions to your de+elopers - $y maintaining backups of ?)) database, you can secure all your code centrally, instead of worrying about indi+idual script files

Das könnte Ihnen auch gefallen