<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearch/1.1/' xmlns:georss='http://www.georss.org/georss' xmlns:thr='http://purl.org/syndication/thread/1.0' xmlns:gd='http://schemas.google.com/g/2005' gd:etag='W/&quot;C0IAQ3oyfCp7ImA9Wx9bGEo.&quot;'><id>tag:blogger.com,1999:blog-7139346007684541452</id><updated>2011-02-27T21:39:02.494-08:00</updated><title>SQL - My Best Friend</title><subtitle type='html'>My experiences and references in SQL server</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://sqlchanakya.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7139346007684541452/posts/default?redirect=false&amp;v=2'/><link rel='alternate' type='text/html' href='http://sqlchanakya.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Chanakya</name><uri>http://www.blogger.com/profile/01914360665067420214</uri><email>noreply@blogger.com</email></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>11</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry gd:etag='W/&quot;C0AMQ3g5eyp7ImA9Wx9bEUk.&quot;'><id>tag:blogger.com,1999:blog-7139346007684541452.post-2780294791093503773</id><published>2011-02-09T05:33:00.000-08:00</published><updated>2011-02-19T10:56:22.623-08:00</updated><app:edited xmlns:app='http://www.w3.org/2007/app'>2011-02-19T10:56:22.623-08:00</app:edited><category scheme='http://www.blogger.com/atom/ns#' term='SQL Scripts'/><title>Calculating Working days</title><content type='html'>Here is a script for finding out the calculating the work days (excluding the saturdays and sundays). The script can be altered also to accomodate local holidays in a separate table too. Only thing is to substract the count of the table for that period.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: html"&gt;&lt;br /&gt;Declare @StartDate Date,  @EndDate Date&lt;br /&gt;Set @StartDate = Getdate()-20&lt;br /&gt;Set @EndDate = Getdate()&lt;br /&gt;&lt;br /&gt;SELECT  (DATEDIFF(dd, @StartDate, @EndDate) + 1)&lt;br /&gt;  -(DATEDIFF(wk, @StartDate, @EndDate) * 2)&lt;br /&gt;  -(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)&lt;br /&gt;  -(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END)&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7139346007684541452-2780294791093503773?l=sqlchanakya.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://sqlchanakya.blogspot.com/feeds/2780294791093503773/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=7139346007684541452&amp;postID=2780294791093503773&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7139346007684541452/posts/default/2780294791093503773?v=2'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7139346007684541452/posts/default/2780294791093503773?v=2'/><link rel='alternate' type='text/html' href='http://sqlchanakya.blogspot.com/2011/02/calculating-working-days.html' title='Calculating Working days'/><author><name>Chanakya</name><uri>http://www.blogger.com/profile/01914360665067420214</uri><email>noreply@blogger.com</email><gd:extendedProperty name='OpenSocialUserId' value='07901708608661769029'/></author><thr:total>0</thr:total></entry><entry gd:etag='W/&quot;A0ANSHs_fSp7ImA9Wx9VGE4.&quot;'><id>tag:blogger.com,1999:blog-7139346007684541452.post-8040257390706856393</id><published>2011-01-08T02:25:00.000-08:00</published><updated>2011-02-04T09:16:39.545-08:00</updated><app:edited xmlns:app='http://www.w3.org/2007/app'>2011-02-04T09:16:39.545-08:00</app:edited><category scheme='http://www.blogger.com/atom/ns#' term='SQL Scripts'/><title>Removing multiple spaces in data</title><content type='html'>I am certain some of us would have really come across a situation that the spaces between data becomes annoying and needs to be removed on request. Many of the solutions have come across multiple blogs and sites with while loop or cursor was really made to think Is there any way???&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Hmm!! On searching my tressure, after a while, found something really interested(I dont really know to whome should give the credit, ofcourse it should go the person.) . The idea was really good and quite simple.Sometimes we do take the things very complicated and dont think about a simple solution.Here it is .......&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;a href="http://2.bp.blogspot.com/_YfYU2pQqlxM/TSg7wO8ne-I/AAAAAAAAAeg/fHrtcRnUPns/s1600/1.jpg"&gt;&lt;img id="BLOGGER_PHOTO_ID_5559759439820979170" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 400px; CURSOR: hand; HEIGHT: 144px; TEXT-ALIGN: center" alt="" src="http://2.bp.blogspot.com/_YfYU2pQqlxM/TSg7wO8ne-I/AAAAAAAAAeg/fHrtcRnUPns/s400/1.jpg" border="0" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;div&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7139346007684541452-8040257390706856393?l=sqlchanakya.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://sqlchanakya.blogspot.com/feeds/8040257390706856393/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=7139346007684541452&amp;postID=8040257390706856393&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7139346007684541452/posts/default/8040257390706856393?v=2'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7139346007684541452/posts/default/8040257390706856393?v=2'/><link rel='alternate' type='text/html' href='http://sqlchanakya.blogspot.com/2011/01/removing-multiple-spaces-in-data.html' title='Removing multiple spaces in data'/><author><name>Chanakya</name><uri>http://www.blogger.com/profile/01914360665067420214</uri><email>noreply@blogger.com</email><gd:extendedProperty name='OpenSocialUserId' value='07901708608661769029'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://2.bp.blogspot.com/_YfYU2pQqlxM/TSg7wO8ne-I/AAAAAAAAAeg/fHrtcRnUPns/s72-c/1.jpg' height='72' width='72'/><thr:total>0</thr:total></entry><entry gd:etag='W/&quot;DUUMRn85fSp7ImA9Wx9RFks.&quot;'><id>tag:blogger.com,1999:blog-7139346007684541452.post-7468884415679891776</id><published>2010-12-18T02:02:00.000-08:00</published><updated>2010-12-18T02:14:47.125-08:00</updated><app:edited xmlns:app='http://www.w3.org/2007/app'>2010-12-18T02:14:47.125-08:00</app:edited><category scheme='http://www.blogger.com/atom/ns#' term='SQL server - Misconceptions'/><title>Table variable myths</title><content type='html'>There are always some myths around the table variable:&lt;br /&gt;1. Table variables works with only memory.&lt;br /&gt;       - It is wrong understanding that the table varibles works only with memory. If table variables are populated with more records, it spills to the temp DB and works as Temperory tables. We need to make sure if the records are less and enough to do the operations in memory, can easily go with the table variable considering the basic differences with temperory table.&lt;br /&gt;&lt;br /&gt;2. Table variables can not be indexed at all.&lt;br /&gt;    - Many of SQL developers think that the table variable can not be indexed. In truth, it can be very well at the declaration part as below:&lt;br /&gt;DECLARE @Test TABLE (&lt;br /&gt;ID INT NOT NULL PRIMARY KEY,&lt;br /&gt;IndexableColumn1 INT,&lt;br /&gt;IndexableColumn2 DATETIME,&lt;br /&gt;IndexableColumn3 VARCHAR(10),&lt;br /&gt;UNIQUE (IndexableColumn1,ID),&lt;br /&gt;UNIQUE (IndexableColumn2,ID),&lt;br /&gt;UNIQUE (IndexableColumn3, IndexableColumn2, ID)&lt;br /&gt;)&lt;br /&gt;3. Changes to table variables are not logged.&lt;br /&gt;       - Even table variables are not part of the transactions(can not be a partof rollback; no effect), it logs the operations. This is for the main reason to avoid any violation to the primary/unique key constraints. Say, inserting a bunch of records to a table varible breaks at the mid of the operations, it has to delete the records from that table variable(Atomicity concept).&lt;br /&gt;&lt;br /&gt;Reference:&lt;br /&gt;&lt;a href="http://sqlinthewild.co.za/index.php/2010/10/12/a-trio-of-table-variables/#more-687"&gt;http://sqlinthewild.co.za/index.php/2010/10/12/a-trio-of-table-variables/#more-687&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7139346007684541452-7468884415679891776?l=sqlchanakya.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://sqlchanakya.blogspot.com/feeds/7468884415679891776/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=7139346007684541452&amp;postID=7468884415679891776&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7139346007684541452/posts/default/7468884415679891776?v=2'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7139346007684541452/posts/default/7468884415679891776?v=2'/><link rel='alternate' type='text/html' href='http://sqlchanakya.blogspot.com/2010/12/table-variable-myths.html' title='Table variable myths'/><author><name>Chanakya</name><uri>http://www.blogger.com/profile/01914360665067420214</uri><email>noreply@blogger.com</email><gd:extendedProperty name='OpenSocialUserId' value='07901708608661769029'/></author><thr:total>0</thr:total></entry><entry gd:etag='W/&quot;DUIHR3s7cCp7ImA9Wx9XEUg.&quot;'><id>tag:blogger.com,1999:blog-7139346007684541452.post-3353903208172251957</id><published>2010-12-16T07:45:00.000-08:00</published><updated>2011-01-04T08:12:16.508-08:00</updated><app:edited xmlns:app='http://www.w3.org/2007/app'>2011-01-04T08:12:16.508-08:00</app:edited><category scheme='http://www.blogger.com/atom/ns#' term='SQL server - Misconceptions'/><title>IF statement resulting in Recompile</title><content type='html'>There is a wrong perception amoung someDBAs that the if statement in procedures would cause a recompile of the procedures at the execution time. However, it is been proved that if a procedure contains if statements, all codes are getting compiled at the first compilation stored in the cache,ie, the cache plan contains all the statements and never been recompiled due to the "if statement".&lt;br /&gt;&lt;a href="http://4.bp.blogspot.com/_YfYU2pQqlxM/TSNGs8s34YI/AAAAAAAAAeY/yRsO21SoEvE/s1600/Untitled.jpg"&gt;&lt;img id="BLOGGER_PHOTO_ID_5558364103127851394" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 400px; CURSOR: hand; HEIGHT: 243px; TEXT-ALIGN: center" alt="" src="http://4.bp.blogspot.com/_YfYU2pQqlxM/TSNGs8s34YI/AAAAAAAAAeY/yRsO21SoEvE/s400/Untitled.jpg" border="0" /&gt;&lt;/a&gt; --Look at the plan created &lt;a href="http://1.bp.blogspot.com/_YfYU2pQqlxM/TSH84lor_cI/AAAAAAAAAeI/xlzrwSgn9f4/s1600/.jpg"&gt;&lt;div&gt;&lt;img id="BLOGGER_PHOTO_ID_5558001464257543618" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 320px; CURSOR: hand; HEIGHT: 100px; TEXT-ALIGN: center" alt="" src="http://1.bp.blogspot.com/_YfYU2pQqlxM/TSH84lor_cI/AAAAAAAAAeI/xlzrwSgn9f4/s320/.jpg" border="0" /&gt;&lt;/a&gt;&lt;/div&gt; From the above figure, it is clear that even you execute the procedure which succeeds for a condition, SQL server would create plan for both cases and utilize the same for the next execution. The issue here is for a procedure with more if and else condition, the plan created may not be suitable and may lead to an unexpected execution plans.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Reference:&lt;br /&gt;&lt;a href="http://www.sqlservercentral.com/blogs/sqlinthewild/archive/2010/12/14/do-if-statements-cause-recompiles_3F00_.aspx"&gt;http://www.sqlservercentral.com/blogs/sqlinthewild/archive/2010/12/14/do-if-statements-cause-recompiles_3F00_.aspx&lt;/a&gt;&lt;br /&gt;&lt;a href="http://scarydba.com/2010/05/11/recompiles-and-constant-learning/"&gt;http://scarydba.com/2010/05/11/recompiles-and-constant-learning/&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7139346007684541452-3353903208172251957?l=sqlchanakya.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://sqlchanakya.blogspot.com/feeds/3353903208172251957/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=7139346007684541452&amp;postID=3353903208172251957&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7139346007684541452/posts/default/3353903208172251957?v=2'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7139346007684541452/posts/default/3353903208172251957?v=2'/><link rel='alternate' type='text/html' href='http://sqlchanakya.blogspot.com/2010/12/if-statement-resulting-in-recompile.html' title='IF statement resulting in Recompile'/><author><name>Chanakya</name><uri>http://www.blogger.com/profile/01914360665067420214</uri><email>noreply@blogger.com</email><gd:extendedProperty name='OpenSocialUserId' value='07901708608661769029'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://4.bp.blogspot.com/_YfYU2pQqlxM/TSNGs8s34YI/AAAAAAAAAeY/yRsO21SoEvE/s72-c/Untitled.jpg' height='72' width='72'/><thr:total>0</thr:total></entry><entry gd:etag='W/&quot;C0IAQ3s4fip7ImA9Wx9bGEo.&quot;'><id>tag:blogger.com,1999:blog-7139346007684541452.post-9005903413569323793</id><published>2010-11-04T04:54:00.000-07:00</published><updated>2011-02-27T21:39:02.536-08:00</updated><app:edited xmlns:app='http://www.w3.org/2007/app'>2011-02-27T21:39:02.536-08:00</app:edited><category scheme='http://www.blogger.com/atom/ns#' term='Performance Tuning'/><title>My Favouirite DMV Queries</title><content type='html'>&lt;span style="color:#000000;"&gt;Performance tuning is really an art in SQL server. I would say whatever you see today would not be the case tomorrow. Oh....oops...I dont mean it really. I wanna say something like tuning for performance is an ongoing activity. Thats better!!! We need more patience and aggressive if we are really need to get some benefits. I would say we need to really understand the SQL server internals and architecture to start with.&lt;br /&gt;Here am giving a check list that I would follow generally. I would like to keep on update the same as I learn things in SQL server(learning new things every day). I just wanna share my experience with performance tuning and looking forward your comments on the same.&lt;br /&gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="color:#009900;"&gt;A. Analysing the wait types and queues.&lt;/span&gt;&lt;br /&gt;&lt;p&gt;&lt;/p&gt;Analysing the wait types are one of the most important aspect of performance tuning for a large systems. SQL server provides information about the performance degradation and can be tracked through analysing the wait types. The following query would provide the most occuring wait types in the production and that can be taken as a first step of your performance tuning of a system.&lt;br /&gt;&lt;pre class="brush: html"&gt;&lt;br /&gt;WITH Waits AS(SELECT &lt;br /&gt;wait_type, &lt;br /&gt;wait_time_ms / 1000.0 AS WaitS, &lt;br /&gt;(wait_time_ms - signal_wait_time_ms) / 1000.0 AS ResourceS, &lt;br /&gt;signal_wait_time_ms / 1000.0 AS SignalS, &lt;br /&gt;waiting_tasks_count AS WaitCount, &lt;br /&gt;100.0 * wait_time_ms / SUM (wait_time_ms) OVER() AS Percentage, &lt;br /&gt;ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS RowNum &lt;br /&gt;FROM sys.dm_os_wait_stats &lt;br /&gt;WHERE wait_type NOT IN ( &lt;br /&gt;'CLR_SEMAPHORE', 'LAZYWRITER_SLEEP', 'RESOURCE_QUEUE', 'SLEEP_TASK', &lt;br /&gt;'SLEEP_SYSTEMTASK', 'SQLTRACE_BUFFER_FLUSH', 'WAITFOR', 'LOGMGR_QUEUE', &lt;br /&gt;'CHECKPOINT_QUEUE', 'REQUEST_FOR_DEADLOCK_SEARCH', 'XE_TIMER_EVENT', 'BROKER_TO_FLUSH',&lt;br /&gt;'BROKER_TASK_STOP', 'CLR_MANUAL_EVENT', 'CLR_AUTO_EVENT', 'DISPATCHER_QUEUE_SEMAPHORE',&lt;br /&gt;'FT_IFTS_SCHEDULER_IDLE_WAIT', 'XE_DISPATCHER_WAIT', 'XE_DISPATCHER_JOIN', 'BROKER_EVENTHANDLER',&lt;br /&gt;'TRACEWRITE', 'FT_IFTSHC_MUTEX', 'SQLTRACE_INCREMENTAL_FLUSH_SLEEP',&lt;br /&gt;'BROKER_RECEIVE_WAITFOR', 'ONDEMAND_TASK_QUEUE', 'DBMIRROR_EVENTS_QUEUE',&lt;br /&gt;'DBMIRRORING_CMD', 'BROKER_TRANSMITTER', 'SQLTRACE_WAIT_ENTRIES',&lt;br /&gt;'SLEEP_BPOOL_FLUSH', 'SQLTRACE_LOCK') &lt;br /&gt;) &lt;br /&gt;SELECT &lt;br /&gt;W1.wait_type AS WaitType, &lt;br /&gt;CAST (W1.WaitS AS DECIMAL(14, 2)) AS Wait_S,&lt;br /&gt;CAST (W1.ResourceS AS DECIMAL(14, 2)) AS Resource_S,&lt;br /&gt;CAST (W1.SignalS AS DECIMAL(14, 2)) AS Signal_S,&lt;br /&gt;W1.WaitCount AS WaitCount,&lt;br /&gt;CAST (W1.Percentage AS DECIMAL(4, 2)) AS Percentage,&lt;br /&gt;CAST ((W1.WaitS / W1.WaitCount) AS DECIMAL (14, 4)) AS AvgWait_S,&lt;br /&gt;CAST ((W1.ResourceS / W1.WaitCount) AS DECIMAL (14, 4)) AS AvgRes_S, &lt;br /&gt;CAST ((W1.SignalS / W1.WaitCount) AS DECIMAL (14, 4)) AS AvgSig_S &lt;br /&gt;FROM Waits AS W1 &lt;br /&gt;INNER JOIN Waits AS W2 ON W2.RowNum &lt;= W1.RowNum GROUP BY W1.RowNum, W1.wait_type, &lt;br /&gt;W1.WaitS, W1.ResourceS, W1.SignalS, W1.WaitCount, W1.Percentage HAVING SUM &lt;br /&gt;(W2.Percentage) - W1.Percentage &lt;95&lt;/pre&gt;&lt;br /&gt;Few of major Wait type and its analysis as follows:&lt;br /&gt;1. &lt;a href="http://sqlchanakya.blogspot.com/2010/12/cxpacket-parallellism.html"&gt;CXPACKET&lt;/a&gt;&lt;br /&gt;&lt;span style="color:#009900;"&gt;B. Analysing the index structures.&lt;/span&gt;&lt;br /&gt;&lt;span style="color:#3366ff;"&gt;1. Clustered Index Structure&lt;br /&gt;2. Non Clustered Index Structure.&lt;br /&gt;&lt;span style="color:#009900;"&gt;C. Implicit Datatype Conversion&lt;/span&gt;&lt;br /&gt;&lt;span style="color:#009900;"&gt;D. Lock Contention/Escalations on Tables&lt;/span&gt;&lt;br /&gt;&lt;span style="color:#33cc00;"&gt;E. Memory Issues&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="color:#3366ff;"&gt;&lt;span style="color:#33cc00;"&gt;F. Look for Spool information&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="color:#3366ff;"&gt;&lt;span style="color:#33cc00;"&gt;G. Look for Index Scans (Clustered/Non-Clustered)&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="color:#33cc00;"&gt;H. Page split and Fragmentation&lt;/span&gt;&lt;br /&gt;&lt;span style="color:#3366ff;"&gt;&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7139346007684541452-9005903413569323793?l=sqlchanakya.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://sqlchanakya.blogspot.com/feeds/9005903413569323793/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=7139346007684541452&amp;postID=9005903413569323793&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7139346007684541452/posts/default/9005903413569323793?v=2'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7139346007684541452/posts/default/9005903413569323793?v=2'/><link rel='alternate' type='text/html' href='http://sqlchanakya.blogspot.com/2010/11/my-favouirite-dmv-queries.html' title='My Favouirite DMV Queries'/><author><name>Chanakya</name><uri>http://www.blogger.com/profile/01914360665067420214</uri><email>noreply@blogger.com</email><gd:extendedProperty name='OpenSocialUserId' value='07901708608661769029'/></author><thr:total>0</thr:total></entry><entry gd:etag='W/&quot;Dk4NSXY_eSp7ImA9Wx9UEEQ.&quot;'><id>tag:blogger.com,1999:blog-7139346007684541452.post-3267765763144666476</id><published>2010-10-02T11:05:00.001-07:00</published><updated>2011-02-07T08:09:58.841-08:00</updated><app:edited xmlns:app='http://www.w3.org/2007/app'>2011-02-07T08:09:58.841-08:00</app:edited><category scheme='http://www.blogger.com/atom/ns#' term='SQL Scripts'/><title>Sequence Numbers in SQL server</title><content type='html'>Have you ever thoguht of generating sequential numbers? I guess, many of us had atleast once a scenario atleast for our reporting purpose to think about sequencing the records.&lt;br /&gt;&lt;br /&gt;Here am going to explain how do I come across with various SQL server versions. We have something like IDENTITY (I will explain little more about this later) in all of SQL versions available. It is a kind of methodology given by SQL server to generate sequencing. How about when you do have scenario to generate the&lt;br /&gt;sequence while you write a procedure.Here we go!!!&lt;br /&gt;&lt;br /&gt;&lt;span style="color:#33cc00;"&gt;&lt;u&gt;SQL Server 2000 &lt;/u&gt;&lt;/span&gt;&lt;br /&gt;&lt;pre class="brush: html";&gt;&lt;br /&gt;SELECT&lt;br /&gt;RowNumber = IDENTITY(INT,1,1)&lt;br /&gt;,c.LastName&lt;br /&gt;,c.FirstName&lt;br /&gt;INTO #Customer_RowID&lt;br /&gt;FROM SalesLT.Customer c&lt;br /&gt;ORDER BY c.LastName ASC&lt;br /&gt;SELECT * FROM #Customer_RowID&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="color:#33cc00;"&gt;&lt;u&gt;&lt;/u&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="color:#33cc00;"&gt;&lt;u&gt;SQL Server 2005 and 2008&lt;/u&gt;&lt;/span&gt;&lt;br /&gt;&lt;pre class="brush: html";&gt;&lt;br /&gt;SELECT PurchaseID, PurchaseDate, ROW_NUMBER() OVER (ORDER BY PurchaseDate) AS 'RowNumber' FROM PurchaseOrder&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="color:#33cc00;"&gt;&lt;u&gt;SQL Server -(Denali)&lt;/u&gt;&lt;/span&gt;&lt;br /&gt;In addition to ROW_NUMBER, there is something called Sequence introduced in Denali Version. I have not got any personal experience with the same.Hence am just giving a clue...&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7139346007684541452-3267765763144666476?l=sqlchanakya.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://sqlchanakya.blogspot.com/feeds/3267765763144666476/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=7139346007684541452&amp;postID=3267765763144666476&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7139346007684541452/posts/default/3267765763144666476?v=2'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7139346007684541452/posts/default/3267765763144666476?v=2'/><link rel='alternate' type='text/html' href='http://sqlchanakya.blogspot.com/2010/10/simulate-rownumber-in-sql-server-2000.html' title='Sequence Numbers in SQL server'/><author><name>Chanakya</name><uri>http://www.blogger.com/profile/01914360665067420214</uri><email>noreply@blogger.com</email><gd:extendedProperty name='OpenSocialUserId' value='07901708608661769029'/></author><thr:total>0</thr:total></entry><entry gd:etag='W/&quot;CUcGQn89eSp7ImA9Wx9bEUk.&quot;'><id>tag:blogger.com,1999:blog-7139346007684541452.post-6022829444478754583</id><published>2009-04-08T21:18:00.001-07:00</published><updated>2011-02-19T11:17:03.161-08:00</updated><app:edited xmlns:app='http://www.w3.org/2007/app'>2011-02-19T11:17:03.161-08:00</app:edited><category scheme='http://www.blogger.com/atom/ns#' term='SQL Scripts'/><title>Rebuild tables in a database</title><content type='html'>The below script will do a rebuilding of indexes of all tables in a database. &lt;br /&gt;&lt;br /&gt;We can explicitly mention the below features for this procedure:&lt;br /&gt;1. Excluded list of tables &lt;br /&gt;2. MAXDOP can be specified.&lt;br /&gt;3. Fillfactor can be specified(by default it takes from the system catalogs.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: html"&gt;&lt;br /&gt;set ANSI_NULLS ON&lt;br /&gt;set QUOTED_IDENTIFIER ON&lt;br /&gt;go&lt;br /&gt;&lt;br /&gt;ALTER PROCEDURE [dbo].[RebuildAllIndexes]&lt;br /&gt;AS&lt;br /&gt;SET NOCOUNT ON;&lt;br /&gt;DECLARE @objectid int;&lt;br /&gt;DECLARE @indexid int;&lt;br /&gt;DECLARE @indexname sysname;&lt;br /&gt;DECLARE @maxdop tinyint;&lt;br /&gt;DECLARE @schemaname nvarchar(130);&lt;br /&gt;DECLARE @objectname nvarchar(130);&lt;br /&gt;DECLARE @partitionnum bigint;&lt;br /&gt;DECLARE @partitions bigint;&lt;br /&gt;DECLARE @frag float;&lt;br /&gt;DECLARE @command nvarchar(4000);&lt;br /&gt;DECLARE @infomessage varchar(1000);&lt;br /&gt;DECLARE @fillfactor tinyint;&lt;br /&gt;DECLARE @returncode tinyint;&lt;br /&gt;DECLARE @dbname sysname;&lt;br /&gt;DECLARE @localerror integer;&lt;br /&gt;DECLARE @ExcludeTableList varchar(100)&lt;br /&gt;&lt;br /&gt;SET @ExcludeTableList = '&lt;tablelist&gt;'+','&lt;br /&gt;SET @dbname = DB_NAME()&lt;br /&gt;&lt;br /&gt;-- Set MAXDOP default value&lt;br /&gt;IF (@maxdop IS NULL)&lt;br /&gt;BEGIN&lt;br /&gt;SET @maxdop = (SELECT CONVERT(smallint, value) FROM master.sys.configurations (NOLOCK) WHERE name = 'max degree of parallelism')&lt;br /&gt;END&lt;br /&gt;SET @returncode = 0&lt;br /&gt;&lt;br /&gt;-- Conditionally select tables and indexes from the sys.dm_db_index_physical_stats function&lt;br /&gt;-- and convert object and index IDs to names.&lt;br /&gt;IF OBJECT_ID('tempdb..#work_to_do') IS NOT NULL&lt;br /&gt;BEGIN&lt;br /&gt;DROP TABLE #work_to_do&lt;br /&gt;END&lt;br /&gt;CREATE TABLE #work_to_do(&lt;br /&gt;[objectid] [int] NULL,&lt;br /&gt;[indexid] [int] NULL,&lt;br /&gt;[fill_factor] [int] NOT NULL&lt;br /&gt;)&lt;br /&gt;-- Get indexes that meet our criteria&lt;br /&gt;INSERT INTO #work_to_do&lt;br /&gt;SELECT o.object_id,i.index_id, CASE i.fill_factor WHEN 0 THEN 100 ELSE i.fill_factor END AS fill_factor&lt;br /&gt;FROM sys.indexes i (NOLOCK) INNER JOIN sys.objects o(nolock) ON i.object_id = o.object_id&lt;br /&gt;WHERE i.index_id &gt; 0 AND o.type ='U' AND CHARINDEX(o.name+',',@ExcludeTableList) = 0&lt;br /&gt;ORDER BY O.name,i.index_id&lt;br /&gt;-- Declare the cursor for the list of partitions to be processed.&lt;br /&gt;DECLARE partitions CURSOR FOR SELECT * FROM #work_to_do;&lt;br /&gt;-- Open the cursor.&lt;br /&gt;OPEN partitions;&lt;br /&gt;-- Loop through the partitions.&lt;br /&gt;WHILE (1=1)&lt;br /&gt;BEGIN;&lt;br /&gt;FETCH NEXT&lt;br /&gt;FROM partitions&lt;br /&gt;INTO @objectid, @indexid, @fillfactor; --@partitionnum, @frag, ;&lt;br /&gt;IF @@FETCH_STATUS &lt; objectname =" QUOTENAME(o.name)," schemaname =" QUOTENAME(s.name)" schema_id =" o.schema_id" object_id =" @objectid;" schemaname =" '[sys]')" indexname =" QUOTENAME(name)" object_id =" @objectid" index_id =" @indexid;" command =" N'ALTER" command =" @command" command =" @command" fillfactor =" '" command =" @command" maxdop =" '" command =" @command" infomessage =" 'Executing" localerror =" @@ERROR"&gt; 0&lt;br /&gt;BEGIN&lt;br /&gt;SET @infomessage = 'Reindex failed with error ' + CAST(@localerror AS varchar(10)) + '.'&lt;br /&gt;RAISERROR (@infomessage, 11, 1) WITH LOG, NOWAIT&lt;br /&gt;SET @returncode = @returncode + 1&lt;br /&gt;END&lt;br /&gt;END;&lt;br /&gt;-- Close and deallocate the cursor.&lt;br /&gt;CLOSE partitions;&lt;br /&gt;DEALLOCATE partitions;&lt;br /&gt;-- Drop the temporary table.&lt;br /&gt;DROP TABLE #work_to_do;&lt;br /&gt;RETURN @returncode&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7139346007684541452-6022829444478754583?l=sqlchanakya.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://sqlchanakya.blogspot.com/feeds/6022829444478754583/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=7139346007684541452&amp;postID=6022829444478754583&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7139346007684541452/posts/default/6022829444478754583?v=2'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7139346007684541452/posts/default/6022829444478754583?v=2'/><link rel='alternate' type='text/html' href='http://sqlchanakya.blogspot.com/2009/04/rebuild-tables-in-database.html' title='Rebuild tables in a database'/><author><name>Chanakya</name><uri>http://www.blogger.com/profile/01914360665067420214</uri><email>noreply@blogger.com</email><gd:extendedProperty name='OpenSocialUserId' value='07901708608661769029'/></author><thr:total>0</thr:total></entry><entry gd:etag='W/&quot;D0YHR3s8eyp7ImA9Wx9UEEQ.&quot;'><id>tag:blogger.com,1999:blog-7139346007684541452.post-6743435034948156465</id><published>2008-08-16T00:23:00.000-07:00</published><updated>2011-02-07T08:12:16.573-08:00</updated><app:edited xmlns:app='http://www.w3.org/2007/app'>2011-02-07T08:12:16.573-08:00</app:edited><category scheme='http://www.blogger.com/atom/ns#' term='SQL Scripts'/><title>Split function to get values from Comma separated string</title><content type='html'>Split function is one of the main string function to split a list of items separated by a character in our daily functions.&lt;br /&gt;&lt;br /&gt;&lt;span style="color:#33cc00;"&gt;&lt;u&gt;1. Using While loop&lt;br /&gt;&lt;/u&gt;&lt;/span&gt;&lt;br /&gt;&lt;pre class="brush: html";&gt;&lt;br /&gt;ALTER FUNCTION [dbo].[Split]&lt;br /&gt;( @List nvarchar(2000),&lt;br /&gt;@SplitOn nvarchar(5)&lt;br /&gt;)&lt;br /&gt;RETURNS @RtnValue table&lt;br /&gt;( Id int identity(1,1),&lt;br /&gt;Value nvarchar(100)&lt;br /&gt;)&lt;br /&gt;AS&lt;br /&gt;BEGIN&lt;br /&gt;While (Charindex(@SplitOn,@List)&gt;0)&lt;br /&gt;Begin&lt;br /&gt;Insert Into @RtnValue (value)&lt;br /&gt;Select&lt;br /&gt;Value = ltrim(rtrim(Substring(@List,1,Charindex(@SplitOn,@List)-1)))&lt;br /&gt;Set @List = Substring(@List,Charindex(@SplitOn,@List)+len(@SplitOn),len(@List))&lt;br /&gt;End&lt;br /&gt;Insert Into @RtnValue (Value)&lt;br /&gt;Select Value = ltrim(rtrim(@List))&lt;br /&gt;Return&lt;br /&gt;END&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7139346007684541452-6743435034948156465?l=sqlchanakya.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://sqlchanakya.blogspot.com/feeds/6743435034948156465/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=7139346007684541452&amp;postID=6743435034948156465&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7139346007684541452/posts/default/6743435034948156465?v=2'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7139346007684541452/posts/default/6743435034948156465?v=2'/><link rel='alternate' type='text/html' href='http://sqlchanakya.blogspot.com/2008/08/spli-function-to-get-values-from-comma.html' title='Split function to get values from Comma separated string'/><author><name>Chanakya</name><uri>http://www.blogger.com/profile/01914360665067420214</uri><email>noreply@blogger.com</email><gd:extendedProperty name='OpenSocialUserId' value='07901708608661769029'/></author><thr:total>0</thr:total></entry><entry gd:etag='W/&quot;D0ANQHw7fyp7ImA9Wx9RFUw.&quot;'><id>tag:blogger.com,1999:blog-7139346007684541452.post-5566247432945187905</id><published>2008-06-09T22:04:00.000-07:00</published><updated>2010-12-16T08:09:51.207-08:00</updated><app:edited xmlns:app='http://www.w3.org/2007/app'>2010-12-16T08:09:51.207-08:00</app:edited><category scheme='http://www.blogger.com/atom/ns#' term='SQL server Linked Server'/><title>Testing the Linked server connectivity From SQL server 2005</title><content type='html'>Have you ever encountered a scenario in SQL Server 2000 where you want to test the connectivity of a linked server configuration via TSQL? This was not possible easily and best handled from client side. But we have now a system stored procedure "sp_testlinkedserver" in SQL Server 2005 that allows you to test linked server connection. This stored procedure takes a linked server name as parameter, tests the connectivity and returns 0 for success &amp;amp; 1 for failure. You can find more details about this stored procedure in the SQL Server 2005 Books Online. Here is how a sample call can look like:&lt;br /&gt;&lt;br /&gt;declare @srvr nvarchar(128), @retval int;&lt;br /&gt;set @srvr = 'my_linked_srvr';&lt;br /&gt;begin try&lt;br /&gt;exec @retval = sys.sp_testlinkedserver @srvr;&lt;br /&gt;end try&lt;br /&gt;begin catch&lt;br /&gt;set @retval = sign(@@error);&lt;br /&gt;end catch;&lt;br /&gt;if @retval &lt;&gt; 0&lt;br /&gt;raiserror('Unable to connect to server. This operation will be tried later!', 16, 2 );&lt;br /&gt;The reason for the try...catch block is left as an exercise to readers!&lt;br /&gt;&lt;br /&gt;Due to lack of exception handling and implementation of OPENQUERY/OPENROWSET/OPENDATASOURCE interfaces it is not possible to do it cleanly. The afore-mentioned interfaces remain the same in SQL Server 2005 also and they perform their validation at compile-time itself. So for example, if the linked server name is incorrect or the parameter to OPENROWSET is invalid you will get an error immediately. You cannot capture such errors within TRY...CATCH also. You need to enclose it in dynamic SQL so it can be caught in the same batch as the TRY...CATCH. EX:&lt;br /&gt;-- below will fail at compile-time itself&lt;br /&gt;-- so the try..catch never executes&lt;br /&gt;begin try&lt;br /&gt;select * from openquery(missing_server, 'select * from sys.tables')&lt;br /&gt;end try&lt;br /&gt;begin catch ... end catch&lt;br /&gt;&lt;br /&gt;-- using dynamic sql will help since the query&lt;br /&gt;-- is evaluated only when the dynamic SQL statement is executed&lt;br /&gt;begin try&lt;br /&gt;exec('select * from openquery(missing_server, ''select * from sys.tables'')')&lt;br /&gt;end try&lt;br /&gt;begin catch ... end catch&lt;br /&gt;This also holds true in SQL Server 2000. Compare code below:&lt;br /&gt;select * from openquery(some_servr, 'select 1')&lt;br /&gt;if @@error &lt;&gt; 0&lt;br /&gt;begin&lt;br /&gt;print 'Error'&lt;br /&gt;end&lt;br /&gt;go&lt;br /&gt;exec('select * from openquery(some_servr, ''select 1'')')&lt;br /&gt;if @@error &lt;&gt; 0&lt;br /&gt;begin&lt;br /&gt;print 'Error'&lt;br /&gt;end&lt;br /&gt;So the bottom-line is that you could use dynamic SQL to run the test statement against remote server and catch any errors. Now, as for your question about different domains there is lot of complexity involved depending on how you want to establish the connection. If you are using SQL logins then it is straight forward assuming the firewall or network settings allow communication between the servers. In case of Windows authentication, you may have to enable constrained delegation (Windows Server 2003) or security delegation depending on service account configurations and from where the clients connect. See BOL for discussion on these topics.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7139346007684541452-5566247432945187905?l=sqlchanakya.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://sqlchanakya.blogspot.com/feeds/5566247432945187905/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=7139346007684541452&amp;postID=5566247432945187905&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7139346007684541452/posts/default/5566247432945187905?v=2'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7139346007684541452/posts/default/5566247432945187905?v=2'/><link rel='alternate' type='text/html' href='http://sqlchanakya.blogspot.com/2008/06/testing-linked-server-connectivity-from.html' title='Testing the Linked server connectivity From SQL server 2005'/><author><name>Chanakya</name><uri>http://www.blogger.com/profile/01914360665067420214</uri><email>noreply@blogger.com</email><gd:extendedProperty name='OpenSocialUserId' value='07901708608661769029'/></author><thr:total>0</thr:total></entry><entry gd:etag='W/&quot;D08GSH0_cSp7ImA9Wx9RFUw.&quot;'><id>tag:blogger.com,1999:blog-7139346007684541452.post-7951222958153192715</id><published>2008-05-28T10:05:00.000-07:00</published><updated>2010-12-16T08:10:29.349-08:00</updated><app:edited xmlns:app='http://www.w3.org/2007/app'>2010-12-16T08:10:29.349-08:00</app:edited><category scheme='http://www.blogger.com/atom/ns#' term='SQL Dead Lock'/><title>Dead Lock Related Topics</title><content type='html'>&lt;span style="color:#3333ff;"&gt;&lt;u&gt;Deadlock Notification&lt;/u&gt;&lt;/span&gt;&lt;br /&gt;Deadlocks... huh??&lt;br /&gt;Deadlocks can be a pain to debug since they're so rare and unpredictable. The problem lies in repeating them in your dev environment. That's why it's crucial to have as much information about them from the production environment as possible.&lt;br /&gt;There are two ways to monitor deadlocks, about which I'll talk about in the future posts. Those are SQL Server tracing and Error log checking. Unfortunately both of them suffer from the same thing: you don't know immediately when a deadlock occurs. Getting this info as soon as possible is sometimes crucial in production environments. Sure you can always set the trace flag 1222 on, but this still doesn't solve the immediate notification problem.&lt;br /&gt;One problem for some might be that this method is only truly useful if you limit data access to stored procedures. &lt;joke&gt;So all you ORM lovers stop reading since this doesn't apply to you anymore! &lt;/joke&gt;&lt;br /&gt;The other problem is that it requires a rewrite of the problematic stored procedures to support it. However since SQL Server 2005 came out my opinion is that every stored procedure should have the try ... catch block implemented. There's no visible performance hit from this and the benefits can be huge. One of those benefits are the instant deadlocking notifications.&lt;br /&gt;&lt;br /&gt;Needed "infrastructure"&lt;br /&gt;So let's see how it done. This must be implemented in the database you wish to monitor of course.&lt;br /&gt;CREATE VIEW vLocks&lt;br /&gt;AS&lt;br /&gt;SELECT L.request_session_id AS SPID,&lt;br /&gt;DB_NAME(L.resource_database_id) AS DatabaseName,&lt;br /&gt;O.Name AS LockedObjectName,&lt;br /&gt;P.object_id AS LockedObjectId,&lt;br /&gt;L.resource_type AS LockedResource,&lt;br /&gt;L.request_mode AS LockType,&lt;br /&gt;ST.text AS SqlStatementText,&lt;br /&gt;ES.login_name AS LoginName,&lt;br /&gt;ES.host_name AS HostName,&lt;br /&gt;TST.is_user_transaction AS IsUserTransaction,&lt;br /&gt;AT.name AS TransactionName&lt;br /&gt;FROM sys.dm_tran_locks L&lt;br /&gt;LEFT JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id&lt;br /&gt;LEFT JOIN sys.objects O ON O.object_id = P.object_id&lt;br /&gt;LEFT JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id&lt;br /&gt;LEFT JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id&lt;br /&gt;LEFT JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id&lt;br /&gt;LEFT JOIN sys.dm_exec_requests ER ON AT.transaction_id = ER.transaction_id&lt;br /&gt;CROSS APPLY sys.dm_exec_sql_text(ER.sql_handle) AS ST&lt;br /&gt;WHERE resource_database_id = db_id()&lt;br /&gt;GO&lt;br /&gt;Next we have to create our stored procedure template:CREATE PROC &lt;procedurename&gt;&lt;br /&gt;AS&lt;br /&gt;BEGIN TRAN&lt;br /&gt;BEGIN TRY&lt;br /&gt;&lt;sproc&gt;&lt;br /&gt;COMMIT&lt;br /&gt;END TRY&lt;br /&gt;BEGIN CATCH&lt;br /&gt;-- check transaction state&lt;br /&gt;IF XACT_STATE() = -1&lt;br /&gt;BEGIN&lt;br /&gt;DECLARE @message xml&lt;br /&gt;-- get our deadlock info FROM the VIEW&lt;br /&gt;SET @message = '&lt;transactionlocks&gt;' + (SELECT * FROM vLocks ORDER BY SPID FOR XML PATH('TransactionLock')) + '&lt;/transactionlocks&gt;'&lt;br /&gt;-- issue ROLLBACK so we don't ROLLBACK mail sending&lt;br /&gt;ROLLBACK&lt;br /&gt;-- get our error message and number&lt;br /&gt;DECLARE @ErrorNumber INT, @ErrorMessage NVARCHAR(2048)&lt;br /&gt;SELECT @ErrorNumber = ERROR_NUMBER(), @ErrorMessage = ERROR_MESSAGE()&lt;br /&gt;-- if it's deadlock error send mail notification&lt;br /&gt;IF @ErrorNumber = 1205&lt;br /&gt;BEGIN&lt;br /&gt;DECLARE @MailBody NVARCHAR(max)&lt;br /&gt;-- create out mail body in the xml format. you can change this to your liking.&lt;br /&gt;SELECT @MailBody = '&lt;deadlocknotification&gt;'&lt;br /&gt;+&lt;br /&gt;(SELECT 'Error number: ' + isnull(CAST(@ErrorNumber AS VARCHAR(5)), '-1') + CHAR(10) +&lt;br /&gt;'Error message: ' + isnull(@ErrorMessage, ' NO error message') + CHAR(10)&lt;br /&gt;FOR XML PATH('ErrorMeassage'))&lt;br /&gt;+&lt;br /&gt;CAST(ISNULL(@message, '') AS NVARCHAR(MAX))&lt;br /&gt;+&lt;br /&gt;'&lt;/deadlocknotification&gt;'&lt;br /&gt;-- for testing purposes&lt;br /&gt;-- SELECT CAST(@MailBody AS XML)&lt;br /&gt;-- send an email with the defined email profile.&lt;br /&gt;-- since this is async it doesn't halt execution&lt;br /&gt;EXEC msdb.dbo.sp_send_dbmail&lt;br /&gt;@profile_name = 'your mail profile',&lt;br /&gt;@recipients = 'dba@yourCompany.com',&lt;br /&gt;@subject = 'Deadlock occured notification',&lt;br /&gt;@body = @MailBody;&lt;br /&gt;END&lt;br /&gt;END&lt;br /&gt;END CATCH&lt;br /&gt;GO&lt;br /&gt;The main part of this stored procedure is of course the CATCH block. The first line in there is check of the &lt;a href="http://msdn.microsoft.com/en-us/library/ms189797.aspx" target="_blank"&gt;XACT_STATE()&lt;/a&gt; value. This is a scalar function that reports the user transaction state. -1 means that the transaction is uncommittable and has to be rolled back. This is the state of the victim transaction in the internal deadlock killing process. Next we read from our vLocks view to get the full info (SPID, both SQL statements text, values, etc...) about both SPIDs that created a deadlock. This is possible since our deadlock victim transaction hasn't been rolled back yet and the locks are still present. We save this data into an XML message. Next we rollback our transaction to release locks. With error message and it's corresponding number we check if the error is 1205 - deadlock and if it is we send our message in an email. How to configure database mail can be seen &lt;a href="http://msdn.microsoft.com/en-us/library/ms175887.aspx" target="_blank"&gt;here&lt;/a&gt;.&lt;br /&gt;Both the view and the stored procedures template can and probably should be customized to suit your needs.&lt;br /&gt;&lt;br /&gt;Testing the theory&lt;br /&gt;Let's try it out and see how it works with a textbook deadlock example that you can find in every book or tutorial.-- create our deadlock table with 2 simple rows&lt;br /&gt;CREATE TABLE DeadlockTest ( id INT)&lt;br /&gt;INSERT INTO DeadlockTest&lt;br /&gt;SELECT 1 UNION ALL&lt;br /&gt;SELECT 2&lt;br /&gt;GO&lt;br /&gt;Next create two stored procedures (spProc1 and spProc2) with our template:&lt;br /&gt;For spProc1 replace &lt;sproc&gt;in the template with: UPDATE DeadlockTest&lt;br /&gt;SET id = 12&lt;br /&gt;WHERE id = 2&lt;br /&gt;&lt;br /&gt;-- wait 5 secs TO SET up deadlock condition IN other window&lt;br /&gt;WAITFOR DELAY '00:00:05'&lt;br /&gt;UPDATE DeadlockTest&lt;br /&gt;SET id = 11&lt;br /&gt;WHERE id = 1&lt;br /&gt;&lt;br /&gt;For spProc2 replace &lt;sproc&gt;in the template with: UPDATE DeadlockTest&lt;br /&gt;SET id = 11&lt;br /&gt;WHERE id = 1&lt;br /&gt;-- wait 5 secs TO SET up deadlock condition IN other window&lt;br /&gt;WAITFOR DELAY '00:00:05'&lt;br /&gt;UPDATE DeadlockTest&lt;br /&gt;SET id = 12&lt;br /&gt;WHERE id = 2&lt;br /&gt;&lt;br /&gt;Next open 2 query windows in SSMS:&lt;br /&gt;In window 1 run put this script:exec spProc1&lt;br /&gt;In window 2 put this script:exec spProc2&lt;br /&gt;&lt;br /&gt;Run the script in the first window and after a second or two run the script in the second window. A deadlock will happen and a few moments after the victim transaction fails you should get the notification mail. Mail profile has to be properly configured of course.&lt;br /&gt;The resulting email should contain an XML with full info about the deadlock. You can view it by commenting msdb.dbo.sp_send_dbmail execution and uncommenting the SELECT CAST(@MailBody AS XML) line.&lt;br /&gt;&lt;br /&gt;If you fire up the SQL Profiler, reset the table values, rerun both scripts and observe the deadlock graph event you should get a picture similar to this one:&lt;br /&gt;&lt;a href="http://weblogs.sqlteam.com/images/weblogs_sqlteam_com/mladenp/WindowsLiveWriter/SQLServer2005SendmailwhenDeadlockhappens_124F2/deadlockProfiler_6.png"&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;End ? ... for now... but more to come soon!&lt;br /&gt;With the upper technique we can get mostly the same info as with trace flags with the advantage of knowing immediately after happening, plus if we want we can extend this to notify/log about every error which I actually prefer to do.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7139346007684541452-7951222958153192715?l=sqlchanakya.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://sqlchanakya.blogspot.com/feeds/7951222958153192715/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=7139346007684541452&amp;postID=7951222958153192715&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7139346007684541452/posts/default/7951222958153192715?v=2'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7139346007684541452/posts/default/7951222958153192715?v=2'/><link rel='alternate' type='text/html' href='http://sqlchanakya.blogspot.com/2008/05/sql-server-2005-immediate-deadlock.html' title='Dead Lock Related Topics'/><author><name>Chanakya</name><uri>http://www.blogger.com/profile/01914360665067420214</uri><email>noreply@blogger.com</email><gd:extendedProperty name='OpenSocialUserId' value='07901708608661769029'/></author><thr:total>0</thr:total></entry><entry gd:etag='W/&quot;D0MFQHo9eip7ImA9Wx9UEEQ.&quot;'><id>tag:blogger.com,1999:blog-7139346007684541452.post-2278748124031897962</id><published>2008-03-10T23:49:00.000-07:00</published><updated>2011-02-07T08:16:51.462-08:00</updated><app:edited xmlns:app='http://www.w3.org/2007/app'>2011-02-07T08:16:51.462-08:00</app:edited><category scheme='http://www.blogger.com/atom/ns#' term='System Functions'/><title>Colasce and ISNULL</title><content type='html'>&lt;span style="color:#ff6600;"&gt;&lt;u&gt;Colaesce &lt;/u&gt;&lt;/span&gt;&lt;br /&gt;&lt;u&gt;&lt;span style="color:#ff6600;"&gt;&lt;/span&gt;&lt;/u&gt;Coalesce and ISNULL are SQL server system functions. Both are using to check the null values in the parameters.&lt;br /&gt;However there are few differences as follows.&lt;br /&gt;1. Coalesce requires atleast two parameters. Can have n number of parameters.&lt;br /&gt;2. Coalesce is an ANSI standard&lt;br /&gt;3. COALESCE works more like a CASE expression, which returns a single datatype depending on precendence and accommodating all possible outcomes&lt;br /&gt;4. Caution using coalesce in sub query; it may create less efficient execution plan.&lt;br /&gt;&lt;br /&gt;&lt;span style="color:#ff6600;"&gt;&lt;u&gt;ISNULL &lt;/u&gt;&lt;/span&gt;&lt;br /&gt;1. ISNULL is not a NASI standard. It has been opted by Microsoft in addition to ANSI. ISNULL() accepts exactly two parameters. If you want to take the first non-NULL among more than two values, you will need to nest your ISNULL() statements. COALESCE(), on the other hand, can take multiple inputs&lt;br /&gt;2. The result of ISNULL() always takes on the datatype of the first parameter (regardless of whether it is NULL or NOT NULL).&lt;br /&gt;3. ISNULL uses an implicit conversion of data type to the first parameter. Beware of these kind of conversions in real time.&lt;br /&gt;&lt;u&gt;&lt;span style="color:#ff6600;"&gt;&lt;/span&gt;&lt;/u&gt;&lt;br /&gt;&lt;u&gt;&lt;span style="color:#ff6600;"&gt;Examples of colaesce usages :&lt;/span&gt;&lt;/u&gt;&lt;br /&gt;&lt;span style="color:#33cc00;"&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="color:#33cc00;"&gt;1. The following query can be improved as follows:&lt;/span&gt;&lt;br /&gt;Where ( DBA_StartdateIs NULL Or DBA_Startdate &lt;= @Startdate) Use the below: Where Colaesce(DBA_Startdate, @Startdate) &lt;= @Startdate&lt;br /&gt;&lt;span style="color:#33cc00;"&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="color:#33cc00;"&gt;2. The following query uses seeks If you wanna check the parameters upon the availability, coalesce/ISNULL can be given as follows to enforce the seeks on the index.&lt;/span&gt;&lt;br /&gt;&lt;pre class="brush: html";&gt;&lt;br /&gt;SELECT * FROM Authors WHERE AU_LName LIKE COALESCE(@lastName, '%')&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;span style="color:#33cc00;"&gt;3. Comma separated string can be created using Colaesce instead of using Cursors&lt;/span&gt;&lt;br /&gt;&lt;pre class="brush: html";&gt;&lt;br /&gt;Declare @TableList Varchar(8000) &lt;br /&gt;Select @TableList = COALESCE(@TableList + ', ', '') +Cast(A.TableName As varchar(50))From Table1 A &lt;br /&gt;Left Join Table2 B On A.TableName = B.TableName &lt;br /&gt;And Convert(Varchar(50),Getdate(),101)= Convert(Varchar(50),B.Date_Column,101)&lt;br /&gt;Where (B.TableName Is Null)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;u&gt;&lt;span style="color:#ff6600;"&gt;Case Study:&lt;/span&gt;&lt;/u&gt;&lt;br /&gt;Createdtwo table T and T2 as the below specifications:/&gt;&lt;br /&gt;&lt;a href="http://1.bp.blogspot.com/_YfYU2pQqlxM/TShJgqJo9VI/AAAAAAAAAfQ/ndigDMNgRzc/s1600/Queries.jpg"&gt;&lt;br /&gt;&lt;a href="http://1.bp.blogspot.com/_YfYU2pQqlxM/TShJgqJo9VI/AAAAAAAAAfQ/ndigDMNgRzc/s1600/Queries.jpg"&gt;&lt;a href="http://1.bp.blogspot.com/_YfYU2pQqlxM/TShJgqJo9VI/AAAAAAAAAfQ/ndigDMNgRzc/s1600/Queries.jpg"&gt;&lt;img id="BLOGGER_PHOTO_ID_5559774565408240978" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 375px; CURSOR: hand; HEIGHT: 227px; TEXT-ALIGN: center" alt="" src="http://1.bp.blogspot.com/_YfYU2pQqlxM/TShJgqJo9VI/AAAAAAAAAfQ/ndigDMNgRzc/s400/Queries.jpg" border="0" /&gt;&lt;/a&gt;The below execution plan is for the coalesce usage. The plan does not have any compute scalara operator as it happens with the ISNULL.&lt;br /&gt;&lt;a href="http://4.bp.blogspot.com/_YfYU2pQqlxM/TShJZHKpbEI/AAAAAAAAAfI/U9b5jR1649Y/s1600/IsNullPlan.jpg"&gt;&lt;img id="BLOGGER_PHOTO_ID_5559774435758140482" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 400px; CURSOR: hand; HEIGHT: 159px; TEXT-ALIGN: center" alt="" src="http://4.bp.blogspot.com/_YfYU2pQqlxM/TShJZHKpbEI/AAAAAAAAAfI/U9b5jR1649Y/s400/IsNullPlan.jpg" border="0" /&gt;&lt;/a&gt; The below figure is XML plan for ISNULL, where an implicit conversion happens for all cases. It does not really not based on any CASE as it happens with the COALESCE.&lt;br /&gt;&lt;br /&gt;&lt;a href="http://3.bp.blogspot.com/_YfYU2pQqlxM/TShJEe7_mkI/AAAAAAAAAfA/Bgx0rhg5gL4/s1600/IsNullXML.jpg"&gt;&lt;img id="BLOGGER_PHOTO_ID_5559774081361877570" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 400px; CURSOR: hand; HEIGHT: 105px; TEXT-ALIGN: center" alt="" src="http://3.bp.blogspot.com/_YfYU2pQqlxM/TShJEe7_mkI/AAAAAAAAAfA/Bgx0rhg5gL4/s400/IsNullXML.jpg" border="0" /&gt;&lt;/a&gt;&lt;br /&gt;The below execution plan is with ISNULL function, where it is clearly showing that an operator in the execution.&lt;br /&gt;&lt;br /&gt;&lt;div&gt;&lt;a href="http://1.bp.blogspot.com/_YfYU2pQqlxM/TShI-tJIFbI/AAAAAAAAAe4/gEK-pGrI_Oo/s1600/coalescePlan.jpg"&gt;&lt;img id="BLOGGER_PHOTO_ID_5559773982095840690" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 400px; CURSOR: hand; HEIGHT: 121px; TEXT-ALIGN: center" alt="" src="http://1.bp.blogspot.com/_YfYU2pQqlxM/TShI-tJIFbI/AAAAAAAAAe4/gEK-pGrI_Oo/s400/coalescePlan.jpg" border="0" /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The XML plan of the query is much more detailed and much more reliable. The below XML plan for the coalesce shows a CASE statement inside an implicit conversion to make the result as discussed above for precendence and accommodating all possible outcomes.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;div&gt;&lt;a href="http://3.bp.blogspot.com/_YfYU2pQqlxM/TShI4TOz2OI/AAAAAAAAAew/CftOuD5YZqY/s1600/colxml.jpg"&gt;&lt;img id="BLOGGER_PHOTO_ID_5559773872061143266" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 400px; CURSOR: hand; HEIGHT: 133px; TEXT-ALIGN: center" alt="" src="http://3.bp.blogspot.com/_YfYU2pQqlxM/TShI4TOz2OI/AAAAAAAAAew/CftOuD5YZqY/s400/colxml.jpg" border="0" /&gt;&lt;/a&gt;&lt;br /&gt;From all the ablove, it always better to look at the XMLplan than graphical representation. Even COALESCE has an implicit conversion of datatype within the CASE, it does not show any indication in the graphical representation of the execution plan.&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;In real time scenarios, lets really evaluate the possible better way between ISNULL and COALESCE for the optimized code. Need to take a call based on your scenario.There is no hard rule found in this case.&lt;/div&gt;&lt;div&gt; &lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;Happy Coding!!!&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;div&gt;&lt;a href="http://3.bp.blogspot.com/_YfYU2pQqlxM/TShIgSP7_eI/AAAAAAAAAeo/0XO649xmg2c/s1600/Queries.jpg"&gt;&lt;/a&gt;&lt;br /&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7139346007684541452-2278748124031897962?l=sqlchanakya.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://sqlchanakya.blogspot.com/feeds/2278748124031897962/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='https://www.blogger.com/comment.g?blogID=7139346007684541452&amp;postID=2278748124031897962&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7139346007684541452/posts/default/2278748124031897962?v=2'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7139346007684541452/posts/default/2278748124031897962?v=2'/><link rel='alternate' type='text/html' href='http://sqlchanakya.blogspot.com/2008/03/optimization-techniques.html' title='Colasce and ISNULL'/><author><name>Chanakya</name><uri>http://www.blogger.com/profile/01914360665067420214</uri><email>noreply@blogger.com</email><gd:extendedProperty name='OpenSocialUserId' value='07901708608661769029'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://1.bp.blogspot.com/_YfYU2pQqlxM/TShJgqJo9VI/AAAAAAAAAfQ/ndigDMNgRzc/s72-c/Queries.jpg' height='72' width='72'/><thr:total>0</thr:total></entry></feed>