<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>&#8235;Madeira&#8236;</title>	<atom:link href="http://www.madeira.co.il/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.madeira.co.il</link>
	<description>&#8235;SQL Server Services&#8236;</description>	<lastBuildDate>Mon, 06 Feb 2012 11:34:44 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>he</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>&#8235;* Select&#8236;</title>		<link>http://www.madeira.co.il/select/</link>
		<comments>http://www.madeira.co.il/select/#comments</comments>
		<pubDate>Sun, 05 Feb 2012 17:46:26 +0000</pubDate>
		<dc:creator>&#8235;יוסי חקיקת&#8236;</dc:creator>				<category><![CDATA[בלוגים]]></category>
		<category><![CDATA[כללי]]></category>
		<category><![CDATA[מקודמות]]></category>
		<category><![CDATA[Performance Tuning]]></category>
		<category><![CDATA[שיפור ביצועים]]></category>

		<guid isPermaLink="false">http://www.madeira.co.il/?p=4121</guid>
		<description><![CDATA[&#8235;במקרים רבים בחיינו אנו כבר רגילים להיזהר מהכוכבית. במודעות פרסום, בחוזים, הסכמים שונים, פרסומות בטלוויזיה, והחל מהיום (אם לא ידעתם...) גם בכל הקשור לסביבת ה- Production של SQL Server. לשימוש ב- * Select ישנן השפעות שלילות לא מעטות וחלקן יכולות להיות משמעותיות ביותר. נכון שמסקרן אתכם לדעת?? כנסו לפוסט....&#8236;]]></description>			<content:encoded><![CDATA[<div dir="rtl"><p><img src='http://www.madeira.co.il/wp-content/plugins/simple-post-thumbnails/timthumb.php?src=/wp-content/thumbnails/4121.jpg&amp;w=214&amp;h=129&amp;zc=1&amp;ft=jpg' alt='post thumbnail' /></p>
<p>SELECT *</p>
<p>מכירים את זה שאתם מגיעים לחתום על חוזה התקשרות עם חברה מסוימת, התנאים נראים מבטיחים, הצעה מעולה ממש עסקת חייכם, אבל אז מגיעים לסוף הדף, ושם באותיות טל ומטר יש כוכבית (או כמה) אשר מבהירות לכם שלא מדובר בעסקת חייכם ולא נעליים. היום כל בר דעת יודע- יש להיזהר מהכוכבית!! אז מעתה והלאה, אני מציע לכם בחום ליישם את הלקח הזה גם בכל הקשור לסביבת ה- Production של SQLServer!! בסביבה זו יש להימנע ככל האפשר מהשימוש ב- *.</p>
<p>אחרי שבפעם האחרונה עסקתי בהרגל מגונה שעיקרו הוספת<span style="color: #0000ff"> </span><span style="color: #0000ff"><a href="http://www.madeira.co.il/nolock/" target="_blank"><span style="color: #0000ff">NOLOCK</span></a> <span style="color: #333333">לכל שאילתה בלי חשבון</span>,</span> היום אעסוק בהרגל מגונה אחר, נפוץ הרבה יותר והוא כאמור * <span style="color: #0000ff">SELECT </span>. בפוסט זה אתייחס לנושא ממספר זוויות והן: הסיבה העיקרית לשימוש ב- *, מתי השימוש לא מזיק, ועיקר הפוסט, ההשפעות השליליות של * <span style="color: #0000ff">SELECT </span>, כן, יש כאלו, ולא מעט!</p>
<p>כאשר מנסים להצדיק את השימוש ב- * <span style="color: #0000ff">SELECT</span> הטענה ראשונה וכמעט היחידה שעולה היא ש- * <span style="color: #0000ff">SELECT </span>חוסך עבודה. נגיד שיש טבלה עם 5 עמודות, ומחר  צריך להוסיף עמודה נוספת, אז לא צריך לשנות את הקוד יותר מדיי, משום ש &#8211; * <span style="color: #0000ff">SELECT </span> לוקח את כל העמודות וזה חוסך זמן, אין צורך  לתקן את הקוד ע&quot;י הוספת העמודות. הטענה השנייה היא דומה, אם ישנן הרבה עמודות בטבלה מסוימת אז זה יותר קל ונוח לרשום * במקום להקליד את כל העמודות. הצד השווה בין שתי הטענות הוא ששורש השימוש ב- * טמון בעצלנות (או חסכון בזמן אם להיות עדינים יותר&#8230;) אז אם אלו הסיבות העיקריות לשימוש ב- *, אז למי שלא מכיר ישנה אפשרות ב- Management Studio להוסיף את כל העמודות הינף קליק. ב- Object Explorer, לכל טבלה יש יש אותן שש עמודות קבועות, אחת מהן היא Columns. עומדים על תיקייה בשם  Columns ופשוט גוררים אותה אל המיקום הרצוי בחלון ה- Query. וזהו! לא צריך להקליד כלום, כל העמודות כתבות לפניכם, מופרדות בפסיקים על מגש של Query.</p>
<p>אז לאחר ששללתי את השימושים העיקריים ב * <span style="color: #0000ff">SELECT</span>, אדגיש כי במקרים לא מעטים השימוש ב * <span style="color: #0000ff">SELECT</span> הוא בסדר גמור ולגיטימי, לדוגמא כאשר רוצים לבצע בדיקות מסוימות או שעובדים עם DMV's שונים. אין שום בעיה במקרים אלו. הבעיות מתחילות שעושים שימוש ב * <span style="color: #0000ff">SELECT </span>בסביבת ה- Production, לדוגמא: * <span style="color: #0000ff">SELECT</span> בפרוצדורות שונות. מה שמוביל אותי לדבר על הצד הפחות זוהר של * <span style="color: #0000ff">SELECT </span>.</p>
<p><span style="text-decoration: underline">ההשפעות השליליות של * <span style="color: #0000ff">SELECT :</span></span></p>
<ul>
<li><strong>פגיעה בשימוש נכון באינדקסים קימיים</strong>- במקרים מסוימים כאשר נריץ שאילתה עם * <span style="color: #0000ff">SELECT </span>, התוצאה הישירה תהיה סקירה מלאה של טבלה או של ה- Clustered Index.  לשם המחשה נריץ את שתי השאילתות הבאות, שימו לב השאילתות זהות במהותן, רק שבראשונה יש שימוש ב- *, ואילו בשנייה כתובות העמודות הרצויות בלבד:</li>
</ul>
<p style="text-align: left"><span style="color: #008000"> :Using SELECT * query &#8211;</span></p>
<p style="text-align: left"><span style="color: #808080">*</span> <span style="color: #0000ff">SELECT</span></p>
<p style="text-align: left"><span style="color: #0000ff">FROM </span>Sales.SalesOrderDetail</p>
<p style="text-align: left"><span style="color: #0000ff">;WHERE</span> ProductID <span style="color: #808080">&lt;</span> 750</p>
<p style="text-align: left"><span style="color: #008000">:Same query as the above but this time, using specific columns &#8211;</span></p>
<p style="text-align: left"><span style="color: #0000ff">SELECT </span>SalesOrderDetailID,ProductID,SalesOrderID</p>
<p style="text-align: left"><span style="color: #0000ff">FROM </span>Sales.SalesOrderDeta</p>
<p style="text-align: left"><span style="color: #0000ff">;WHERE </span>ProductID<span style="color: #808080"> &lt;</span> 750</p>
<p style="text-align: right">נציץ ב- Execution plan:</p>
<p style="text-align: right">
<div id="attachment_4140" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.madeira.co.il/wp-content/uploads/2012/02/ExecutionPlan1.png" rel="wp-prettyPhoto[g4121]"><img class="size-medium wp-image-4140" src="http://www.madeira.co.il/wp-content/uploads/2012/02/ExecutionPlan1-300x116.png" alt="" width="300" height="116" /></a><p class="wp-caption-text">לחץ להגדלה</p></div>
<p style="text-align: right">השאילתה הראשונה (עם * ), עולה כמעט פי 50 מהשאילתה שמציינת במפורש שדות ספציפיים. הסיבה לכך נעוצה בעובדה ששאילתה מספר 1 גורמת לסקירה מלאה של ה- Clustered Index ( שווה ערך פחות או יותר סריקה מלאה של הטבלה). ואילו בשאילתה מספר 2 בוצעה סריקה של ה- Index NonClustered שבמקרה זה, היא פעולה הרבה פחות כבדה. זאת ועוד, במקרים אחרים, שימוש ב- * <span style="color: #0000ff">SELECT </span> גורר פעולות מיותרות אחרות(וכבדות!!) כמו Lookups. לדוגמא אם נריץ את אותן שאילתות מהדוגמא הקודמת אך נשנה את התנאי ב- WHERE ל-  20 אז נוכל לראות ששאילתה מספר 1 גורמת לפעולת lookups שהיא בעצם החלק הכבד של השאילתה (50% מעלות השאילתה מוקדשת לכך). ואילו באפשרות השנייה, מתבצע Index seek על NonClustered IX_SalesOrderDetail_ProductID, שהיא יעילה בהרבה.</p>
<p style="text-align: right">
<div id="attachment_4143" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.madeira.co.il/wp-content/uploads/2012/02/ExecutionPlanWithWhere20.png" rel="wp-prettyPhoto[g4121]"><img class="size-medium wp-image-4143" src="http://www.madeira.co.il/wp-content/uploads/2012/02/ExecutionPlanWithWhere20-300x135.png" alt="" width="300" height="135" /></a><p class="wp-caption-text">לחץ על התמונה להגדלה</p></div>
<ul style="text-align: right">
<li><strong>יצירת עומס על השרת</strong>- אז כפי שהרגע ראינו במקרים רבים שימוש ב * <span style="color: #0000ff">SELECT </span>גורם לסריקות של טבלאות או אינדקסים בצורה לא יעילה ולא נחוצה. ישנם מקרים רבים בהם השאילתה מחזירה לאפליקציה נתונים שאין בהם שום שימוש, משום שהשאילתה מחזירה 10 עמודות לדוגמא, אך האפליקציה מציגה רק 3 עמודות מתוך ה- 10. העומס מתבטא הן בפעולות I/O רבות שאיו בהן צורך, והן במעבר של נתונים ברשת שגם בהם כמובן אין שום שימוש.</li>
<li><strong>שינוי סכמה ב- </strong><strong>View</strong>-  כאשר יוצרים View בעזרת * <span style="color: #0000ff">SELECT </span> ישנה בעיה עיקרית אחת. נניח שלאחר זמן מה, מחליטים לשנות את שם אחת העמודות מ- Bla ל- Bla2. ה-MetaDta של ה- View לא מתעדכן באופן אוטומטי על השינוי, ואין לו מושג שעמודה מסוימת כבר לא נקראת כפי שהיא נקראה בעבר. נסבך את העניינים עוד טיפה, תארו לכם שעכשיו נוסיף עמודה חדשה שנקראת Bla והיא בכלל מסוג אחר(עמודת תאריך במקום מספר שהיה עד כה)במצב זה אנו נקבל ונציג מידע שגוי. (אציין כי ניתן למנוע מצב זה בעזרת שימוש ב- SCHEMABINDING אשר לא מאפשר שימוש ב- * <span style="color: #0000ff">SELECT</span>).</li>
<li><strong>· </strong><strong>ניטור שגיאות- </strong> על מנת להמחיש את הנקודה הבאה אגש ישר לדוגמא ישנה פרוצדורה שמקבלת כפרמטר את rowguid@  ומחזירה נתונים: <strong> </strong></li>
</ul>
<p style="text-align: left">* <span style="color: #0000ff">SELECT</span></p>
<p style="text-align: left"><span style="color: #0000ff">FROM </span>Sales.SalesOrderDetail</p>
<p style="text-align: left"><span style="color: #0000ff">WHERE </span>rowguid = @rowguid</p>
<p style="text-align: right">מחר, הטבלה תעבור שינוי ועמודת RowGuid תימחק מן הטבלה. מי שמחק את הטבלה בטוח שלא צריך לעשות שום שינוי ב- SQL משום שהוא שולף נתונים בעזרת * <span style="color: #0000ff">SELECT</span>. אבל משום שהסינון נעשה על עמודה שלא קיימת עוד, נקבל הודעת שגיאה, ואם אין ניטור מסודר של הודעות השגיאה, אז נקבל הודעת שגיאה עלומה, ועכשיו נצטרך להפוך עולמות עד אשר נגלה את הבעיה האמיתית.</p>
<p style="text-align: right">לסיכום, * <span style="color: #0000ff">SELECT </span>נוח לשימוש ויעיל כל עוד לא משתמשים בו באופן קבוע בסביבת Production. בסביבה זו, יש לשאוף למצב שלא יהיה כלל שימוש ב * <span style="color: #0000ff">SELECT</span>. אם וכאשר נגיע למצב שבו אין שימוש ב * <span style="color: #0000ff">SELECT</span>, אנו נרוויח מכך מהרבה בחינות כפי שהוסבר בפוסט זה,</p>
<p style="text-align: right">מקווה שנהניתם לקרוא,</p>
<p style="text-align: right">חקיקת יוסי</p>
</div>]]></content:encoded>			<wfw:commentRss>http://www.madeira.co.il/select/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>&#8235;Log Shipping – As easy as 1, 2, 3&#8236;</title>		<link>http://www.madeira.co.il/log-shipping-%e2%80%93-as-easy-as-1-2-3/</link>
		<comments>http://www.madeira.co.il/log-shipping-%e2%80%93-as-easy-as-1-2-3/#comments</comments>
		<pubDate>Thu, 02 Feb 2012 08:44:18 +0000</pubDate>
		<dc:creator>&#8235;Shay Attiya&#8236;</dc:creator>				<category><![CDATA[בלוגים]]></category>
		<category><![CDATA[כללי]]></category>
		<category><![CDATA[מקודמות]]></category>
		<category><![CDATA[High Availability]]></category>
		<category><![CDATA[Log Shipping]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Standby Server]]></category>

		<guid isPermaLink="false">http://www.madeira.co.il/?p=4076</guid>
		<description><![CDATA[&#8235;Log Shipping is an easy way to implement a high availability solution. As easy as 1, 2, 3&#8236;]]></description>			<content:encoded><![CDATA[<div dir="rtl"><p><img src='http://www.madeira.co.il/wp-content/plugins/simple-post-thumbnails/timthumb.php?src=/wp-content/thumbnails/4076.png&amp;w=214&amp;h=129&amp;zc=1&amp;ft=jpg' alt='post thumbnail' /></p>
<p dir="ltr">Today I want to talk about Log Shipping.</p>
<p dir="ltr">Log Shipping is an easy way to implement a high availability solution. It uses SQL Server’s transaction log to synchronize a stand by server. The configuration of the log shipping is really easy to set up as I’m about to show.</p>
<p dir="ltr"><strong>Basic requirements:</strong></p>
<p dir="ltr"><strong> </strong>1) The Primary Server must be in “Full” or “Bulk-Logged” recovery model</p>
<p dir="ltr">2) The Secondary Server must be from the same version as the primary (or later) and can be either in “Standby” or “No Recovery” mode. When using the Standby mode, the server can be used for reporting purposes, but it won’t be accessible during the log shipping process.</p>
<p dir="ltr">3) A third monitor server can be used but this is <span style="text-decoration: underline">optional</span>.</p>
<p dir="ltr"><strong>Step 1 – Configuring the Primary Server:</strong></p>
<p dir="ltr">Right click on the DB you wish to log ship and go to “Tasts -&gt; Ship Transaction Logs…”. Click on “Enable this as a primary database in a log shipping configuration” check box and press on the “Backup Settings…” button.</p>
<p dir="ltr"><a href="http://www.madeira.co.il/wp-content/uploads/2012/02/Database-Properties-1.jpg" rel="wp-prettyPhoto[g4076]"><img class="alignnone size-medium wp-image-4079" src="http://www.madeira.co.il/wp-content/uploads/2012/02/Database-Properties-1-300x143.jpg" alt="" width="300" height="143" /></a></p>
<p dir="ltr">The “Transaction Log Backup Settings” window will open. In it you will have to specify the path to the folder where the transaction log backups will be saved. Here you can also determine the frequency of transaction log backups (the default is every 15 minutes).</p>
<p dir="ltr"><a href="http://www.madeira.co.il/wp-content/uploads/2012/02/Transaction-Log-Backup-Settings.jpg" rel="wp-prettyPhoto[g4076]"><img class="alignnone size-medium wp-image-4080" src="http://www.madeira.co.il/wp-content/uploads/2012/02/Transaction-Log-Backup-Settings-291x300.jpg" alt="" width="291" height="300" /></a></p>
<p dir="ltr"><strong>Step 2 – Configuring the Secondary Server:</strong></p>
<p dir="ltr">After the primary server is configured, it’s time to configure the secondary server by pressing the “Add” button. <span style="text-decoration: underline">More than one</span> secondary server can be defined to create multiple standby servers.</p>
<p dir="ltr"><a href="http://www.madeira.co.il/wp-content/uploads/2012/02/Database-Properties-2.jpg" rel="wp-prettyPhoto[g4076]"><img class="alignnone size-medium wp-image-4081" src="http://www.madeira.co.il/wp-content/uploads/2012/02/Database-Properties-2-300x144.jpg" alt="" width="300" height="144" /></a></p>
<p dir="ltr">First, you’ll have to connect to the secondary server.</p>
<p dir="ltr"><a href="http://www.madeira.co.il/wp-content/uploads/2012/02/Secondary-Database-Settings1.jpg" rel="wp-prettyPhoto[g4076]"><img class="alignnone size-medium wp-image-4083" src="http://www.madeira.co.il/wp-content/uploads/2012/02/Secondary-Database-Settings1-300x261.jpg" alt="" width="300" height="261" /></a></p>
<p dir="ltr">
<p dir="ltr">In the <strong>“Initialize Secondary Database”</strong> tab you can choose the way you wish to initialize the secondary database (this is pretty self-explanatory).</p>
<p dir="ltr">In the <strong>“Copy Files”</strong> tab you’ll need to specify the folder where you wish to save the log backups shipped from the primary server, and the frequency of copying between the servers.</p>
<p dir="ltr"><a href="http://www.madeira.co.il/wp-content/uploads/2012/02/Copy-Files.jpg" rel="wp-prettyPhoto[g4076]"><img class="alignnone size-medium wp-image-4084" src="http://www.madeira.co.il/wp-content/uploads/2012/02/Copy-Files-300x260.jpg" alt="" width="300" height="260" /></a></p>
<p dir="ltr">In the <strong>“Restore Transaction Log”</strong> tab you can select the mode you want the secondary server to be in, and determine how often the transaction log will be restored.</p>
<p dir="ltr">As explained in the beginning, choosing the “Standby” mode will allow users to access the secondary DB. This may prevent the log from being restored and fail the log shipping process. When choosing this mode, it’s highly recommended to enable the “Disconnect users” option.</p>
<p dir="ltr"><a href="http://www.madeira.co.il/wp-content/uploads/2012/02/Restore-Transaction-Log.jpg" rel="wp-prettyPhoto[g4076]"><img class="alignnone size-medium wp-image-4085" src="http://www.madeira.co.il/wp-content/uploads/2012/02/Restore-Transaction-Log-300x262.jpg" alt="" width="300" height="262" /></a></p>
<p dir="ltr"><strong>Step 3 – Monitor Server (Optional):</strong></p>
<p dir="ltr">After configuring both servers, you can configure a third, monitor server.</p>
<p dir="ltr">The monitor server keeps track of when the transaction log on the primary database was last backed up, when the secondary servers last copied and restored the backup files, and information about any backup failure alerts.</p>
<p dir="ltr">A single monitor server can monitor multiple log shipping configurations.</p>
<p dir="ltr"><a href="http://www.madeira.co.il/wp-content/uploads/2012/02/Monitor.jpg" rel="wp-prettyPhoto[g4076]"><img class="alignnone size-medium wp-image-4086" src="http://www.madeira.co.il/wp-content/uploads/2012/02/Monitor-300x142.jpg" alt="" width="300" height="142" /></a></p>
<p dir="ltr">You can also generate a script for all of the configurations made to reuse on other servers.</p>
<p dir="ltr"><strong>That’s it!!</strong></p>
<p dir="ltr">You’re all done. After pressing “OK” you should see the following window, and the log shipping is up and running.</p>
<p dir="ltr"><a href="http://www.madeira.co.il/wp-content/uploads/2012/02/DONE.jpg" rel="wp-prettyPhoto[g4076]"><img class="alignnone size-medium wp-image-4087" src="http://www.madeira.co.il/wp-content/uploads/2012/02/DONE-300x155.jpg" alt="" width="300" height="155" /></a></p>
<p dir="ltr"><strong>Created objects:</strong></p>
<p dir="ltr">You might have guessed that the log shipping solution is actually implemented using a series of jobs.</p>
<p dir="ltr">On the primary server you’ll find a job responsible for backing up the log file as specified in the first step.</p>
<p dir="ltr">On the secondary server you’ll find two jobs. The first is responsible for copying the file from the primary to the secondary server, and the second is responsible for restoring the log file as defined in the second step.</p>
<p dir="ltr">On the monitor server you’ll find a job responsible for alerting when no restore has occurred.</p>
<p dir="ltr">You should also find the original log backups on the folder you specified on the primary server, and the copied ones on the secondary.</p>
<p dir="ltr"><strong>Fail Over:</strong></p>
<p dir="ltr">There’s <strong><span style="text-decoration: underline">no automatic fail over</span></strong> when using log shipping.</p>
<p dir="ltr">Performing the manual fail over involves two simple steps</p>
<p dir="ltr">1) Restoring the secondary server with recovery</p>
<p dir="ltr">2) Disable all the related jobs</p>
<p dir="ltr"><strong>Pros and Cons:</strong></p>
<p dir="ltr">I'll start with the good stuff. It’s easy! The default configuration shouldn’t take more than a few minutes to set up. In addition, the standby server can be used for reporting purposes and can be configured on the same instance.</p>
<p dir="ltr">The bad news is the frequent backups add overhead to SQL Server’s operation, and the copying of the backup files takes its toll on the disk subsystem. Another drawback is that fail over must be done manually. If an automatic fail over is important, mirroring might be a more suitable solution.</p>
<p dir="ltr">
</div>]]></content:encoded>			<wfw:commentRss>http://www.madeira.co.il/log-shipping-%e2%80%93-as-easy-as-1-2-3/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>&#8235;The Dedicated administrator connection&#8236;</title>		<link>http://www.madeira.co.il/the-dedicated-administrator-connection/</link>
		<comments>http://www.madeira.co.il/the-dedicated-administrator-connection/#comments</comments>
		<pubDate>Mon, 30 Jan 2012 20:53:25 +0000</pubDate>
		<dc:creator>&#8235;צ'יקו דרורי&#8236;</dc:creator>				<category><![CDATA[בלוגים]]></category>
		<category><![CDATA[כללי]]></category>
		<category><![CDATA[מאמרים]]></category>
		<category><![CDATA[מקודמות]]></category>
		<category><![CDATA[DAC]]></category>
		<category><![CDATA[Dedicated administrator connection]]></category>
		<category><![CDATA[SQL Server 2008 R2]]></category>
		<category><![CDATA[Troubleshooting]]></category>

		<guid isPermaLink="false">http://www.madeira.co.il/?p=4044</guid>
		<description><![CDATA[&#8235;Ever been in a crisis that your SQL Server didn’t respond to standard connection requests? thought that your  last resort was to reboot the  server? This probably because you either haven’t met or forgotten to turn on the DAC your secret backdoor connection to SQL Server&#8236;]]></description>			<content:encoded><![CDATA[<div dir="rtl"><p><img src='http://www.madeira.co.il/wp-content/plugins/simple-post-thumbnails/timthumb.php?src=/wp-content/thumbnails/4044.png&amp;w=214&amp;h=129&amp;zc=1&amp;ft=jpg' alt='post thumbnail' /></p>
<p dir="ltr"><span style="font-size: small">Ever been in a crisis that your SQL Server had a spinloop, maxed out resources or severe corruption and  didn’t respond to standard connection requests, and  With pressure mounting to get SQL Server back online you thought that your  last resort was to reboot the server?</span></p>
<p dir="ltr"><span style="font-size: small">This probably because you either haven’t met or forgotten to turn on the<strong> DAC</strong> your secret backdoor Privilege connection that SQL server offers to us.</span></p>
<h5 style="text-align: left"><span style="font-weight: bold;font-size: medium">DAC? What’s That?</span></h5>
<p dir="ltr"><span style="font-size: small">Since SQL Server 2005, Microsoft offers us new feature, the dedicated administrator connection (DAC) a special diagnostic connection for administrators. This diagnostic connection intended to serve as a last means of defense and access SQL Server to execute diagnostic queries and troubleshoot problems even when SQL Server is not responding to standard connection requests as opposed to rebooting the server and causing us long downtime and  possibly data loss, database corruption and/or access violations. </span></p>
<h5 style="text-align: left"><strong><span style="font-size: small"><span style="font-size: medium">How the DAC works</span> </span></strong></h5>
<p dir="ltr"><span style="font-size: small">SQL Server is keeping a backdoor open  resources available just for the DAC, it uses a<span style="color: #0000ff"> </span></span><a href="http://msdn.microsoft.com/en-us/library/ms177526.aspx"><span style="color: #0000ff;font-size: small">special reserved scheduler</span></a><span style="font-size: small"> (scheduler_id = 255)  which has one thread for processing requests.</span></p>
<p dir="ltr"><span style="font-size: small">We are all DBA’s and I know that to many of you the thought of abuse thus resources for your maintenance jobs on busy systems cross your mind. Seriously, just don’t go there.That one thread is just one thread, there’s no parallelism for queries running on the DAC. The DAC was not designed for high performance.</span></p>
<h5 style="text-align: left"><span style="font-weight: bold;font-size: medium">some restrictions</span></h5>
<p dir="ltr"><span style="font-size: small">Because the DAC exists solely for diagnosing server problems, there are some restrictions on the connection:</span></p>
<div style="line-height: normal;margin-top: 12pt;text-indent: -0.5in;direction: ltr;margin-bottom: 0pt;margin-left: 0.5in"><strong><span style="color: #000000"><span style="font-size: small"><span>Only </span><span>member of </span><span>sysadmin</span><span> </span><span>role </span><span>can </span><span>use </span><span>DAC.</span></span></span></strong></div>
<p dir="ltr"><strong><span style="font-size: small">Only One Sysadmin Can Ride This Horse At a Time.</span></strong></p>
<p dir="ltr"><span style="font-size: small"><strong>SQL Server prohibits running parallel queries or commands with the DAC -</strong> For example statements like RESTORE and BACKUP.</span></p>
<p dir="ltr"><span style="font-size: small"><strong>Do not use the DAC to run resource-intensive queries -</strong> For example a complex join on large table or queries that may block.</span></p>
<p dir="ltr"><span style="font-size: small"><strong>Object Explorer Not available for DAC connection -</strong> That’s a good thing, we wouldn’t want the power to go to Object Explorer’s head.</span></p>
<h5 style="text-align: left"><strong><span style="font-size: medium">Connecting with DAC</span></strong></h5>
<p dir="ltr"><span style="font-size: small">By default, the connection is only allowed  from a client running on the local machine. To enable remote clients to utilize the DAC, an option needs to be <span style="color: #333333">set</span><span style="color: #333333"> which can be done using <span style="color: #d16349">sp_configure</span>:</span></span></p>
<div style="text-align: left;padding: 4px;line-height: 12pt;background-color: #f4f4f4;margin: 20px 0px 10px;width: 97.71%;font-family: 'Courier New',courier,monospace;direction: ltr;height: 52px;font-size: 8pt;overflow: auto;cursor: text;border: 1px solid silver">
<div style="border-style: none;text-align: left;padding: 0px;line-height: 12pt;background-color: #f4f4f4;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible">
<pre style="border-style: none;text-align: left;padding: 0px;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible"><span style="font-family: Arial"><span style="font-size: small"><span style="color: #606060">   1:</span> <span style="color: #0000ff">exec</span> sp_configure <span style="color: #006080">'remote admin connections'</span>, 1 </span></span></pre>
<p><!--CRLF--></p>
<pre style="border-style: none;text-align: left;padding: 0px;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible"><span style="font-family: Arial"><span style="font-size: small"><span style="color: #606060">   2:</span> <span style="color: #0000ff">reconfigure</span></span></span></pre>
<p><!--CRLF--></p>
</div>
</div>
<p dir="ltr"><span style="font-size: small">it’s Highly recommended to enable the ‘remote admin connections’, Especially on clusters configuration. According to BOL servers in cluster configuration and with ‘remote admin connections’ not enable probably Not receive a DAC connection And you can not escape from rebooting the server.</span></p>
<p dir="ltr"><span style="font-size: small">You may need to get firewall ports opened as well, depending on your environment and where you intend to connect from. SQL Server listens for the DAC on TCP port 1434 if available or a TCP port dynamically assigned upon Database Engine startup. The error log contains the port number the DAC is listening on.</span></p>
<p dir="ltr"><strong><span style="font-size: small">To use the DAC you can either access it using<span style="color: #0000ff"> </span></span></strong><a href="http://msdn2.microsoft.com/en-us/ms170207.aspx"><span style="color: #0000ff;font-size: small"><strong>SQLCMD</strong></span></a><strong><span style="font-size: small"> from a command prompt:</span></strong></p>
<p dir="ltr"><span style="font-size: small"><strong>sqlcmd –A –d master </strong>(the -A uses the DAC and the -d connects to the master database) </span></p>
<p dir="ltr"><span style="font-size: small"><strong>sqlcmd –d DBname-E –S ServerName\InstanceName –A</strong> (the -E uses Windows authentication and the -S connects the server and instance)</span></p>
<p dir="ltr"><a href="$Picture1[7].png"><span style="font-size: small"> </span></a><a href="http://www.madeira.co.il/wp-content/uploads/2012/01/Picture1.png" rel="wp-prettyPhoto[g4044]"><img class="aligncenter size-medium wp-image-4053" src="http://www.madeira.co.il/wp-content/uploads/2012/01/Picture1-300x57.png" alt="" width="300" height="57" /></a></p>
<p dir="ltr"><strong><span style="font-size: small">Or The more convenient way is using SQL Management Studio with the ADMIN: option when connecting to the server:</span></strong></p>
<p dir="ltr"><span style="font-size: small">- launch SQL Server Management Studio (don't connect to an instance of SQL Server yet) </span></p>
<p dir="ltr"><span style="font-size: small">- <strong>select Database Engine Query (icon right next to &quot;New Query&quot;) </strong></span></p>
<p dir="ltr"><span style="font-size: small">- <strong>put &quot;ADMIN:&quot; in front of the server\instance name </strong></span></p>
<p dir="ltr"><span style="font-size: small">- <strong>use your regular Authentication procedures to connect </strong></span></p>
<p dir="ltr"><span style="font-size: small">- <strong>select Connect</strong></span></p>
<p dir="ltr"><a href="$Picture2[9].png"><span style="font-size: small"> </span></a><a href="http://www.madeira.co.il/wp-content/uploads/2012/01/Picture2.png" rel="wp-prettyPhoto[g4044]"><img class="aligncenter size-medium wp-image-4054" src="http://www.madeira.co.il/wp-content/uploads/2012/01/Picture2-300x196.png" alt="" width="300" height="196" /></a></p>
<p dir="ltr"><span style="font-size: small"><strong>Note:</strong> Object Explorer can’t connect to the DAC. If you open SSMS and have Object Explorer connecting by default, the first connection prompt you see with be for that. If you try to tell that to connect to the DAC, it’ll fail.</span></p>
<h5 style="text-align: left"><span style="font-size: medium"><span style="font-weight: bold"> </span><span style="font-weight: bold">conclusion </span></span></h5>
<p dir="ltr"><span style="font-size: small">In previous versions of SQL Server it was often not possible to diagnose a SQL Server instance which was no longer accepting connections. With DAC an administrator has a guaranteed connection to the SQL Server, and is able to resolve problems without the need for a reboot, or restarting the SQL server instance.</span></p>
<p dir="ltr"><span style="font-size: small">For now check whether you have remote admin connections enabled in your environments and try to connect with the DAC in test environment </span></p>
</div>]]></content:encoded>			<wfw:commentRss>http://www.madeira.co.il/the-dedicated-administrator-connection/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>&#8235;?READPAST what is it good for&#8236;</title>		<link>http://www.madeira.co.il/readpast-what-is-it-good-for/</link>
		<comments>http://www.madeira.co.il/readpast-what-is-it-good-for/#comments</comments>
		<pubDate>Wed, 25 Jan 2012 19:33:18 +0000</pubDate>
		<dc:creator>&#8235;Tomer Shtrum&#8236;</dc:creator>				<category><![CDATA[בלוגים]]></category>
		<category><![CDATA[כללי]]></category>
		<category><![CDATA[מקודמות]]></category>

		<guid isPermaLink="false">http://www.madeira.co.il/?p=3890</guid>
		<description><![CDATA[&#8235;
After my last post about monitoring deadlocks I will now show a way to prevent <a href="http://www.madeira.co.il/readpast-what-is-it-good-for/"><strong>לסיפור המלא...</strong></a>&#8236;]]></description>			<content:encoded><![CDATA[<div dir="rtl"><p><img src='http://www.madeira.co.il/wp-content/plugins/simple-post-thumbnails/timthumb.php?src=/wp-content/thumbnails/3890.jpg&amp;w=214&amp;h=129&amp;zc=1&amp;ft=jpg' alt='post thumbnail' /></p>
<p dir="ltr">After my last post about <a href="http://www.madeira.co.il/monitoring-deadlocks/" target="_blank">monitoring deadlocks</a> I will now show a way to prevent deadlock and unnecessary locks and to improve system performance.<br />
<strong>Introduction:<br />
</strong>SQL server has a lot of working mechanisms. The lock mechanism is one of the most important mechanism. Its goal is to keep and secure the data reliability and consistently. This mechanism is very complex and depends on many variables. The mechanism is design to let the system work in the optimal way. It is based on the concept of &quot;all or nothing at all&quot;, which means either everything happens during a transaction or nothing happens at all. In specific cases we would like to intervene by setting lock options manually and by doing so to affect the lock mechanism. It is not recommended to use those options on a daily bases, only on specific cases, when we know the type of data that we are dealing with (whether we are receiving data or want to make changes).<br />
The option I am about to present is called &quot;Readpast&quot;. Readpast simply means that when we reach for a table data (select, update or delete) and one or more of the table rows or pages are locked by one or more transactions the lock mechanism will ignore those rows and retrieve the rest of the data which is not locked.<br />
The advantage is obviously a performance improvement because there is no waiting time for another transactions locks. But, the disadvantage is more significant than the advantage because even if we accept the loss of data we will not be able to know which part we lost and when.</p>
<p dir="ltr">The most common and recommendable way to use Readpast is when there is a need to implement a queue of command list. For example: there is a table which each row represents a command that needs to be executed. The table also has a separate and an independent process that inserts new commands every time. The order of the commands is not important as long as they are being done. That is why Readpast is the ultimate solution because each process that will turn to the table will receive the next command with no waiting time.</p>
<p dir="ltr"><strong>Here is a simple example of how Readpast option impacts the lock mechanism:</strong></p>
<p dir="ltr"><strong> <em> · Create a new table with two columns (command ID, command description).</em></strong></p>
<p dir="ltr"><em><strong> · Populate five new rows.</strong></em></p>
<div>
<div>
<pre style="text-align: left"><span style="color: #0000ff">CREATE</span> <span style="color: #0000ff">TABLE</span> ReadPastTest</pre>
<p style="text-align: left"><!--CRLF--></p>
<pre style="text-align: left">)</pre>
<p style="text-align: left"><!--CRLF--></p>
<pre style="text-align: left">CommandId <span style="color: #0000ff">INT</span>, CommandDescription <span style="color: #0000ff">VARCHAR</span>(<span style="color: #0000ff">MAX </span></pre>
<pre style="text-align: left">(</pre>
<p style="text-align: left"><!--CRLF--></p>
<pre style="text-align: left"><span style="color: #0000ff">GO </span></pre>
<p style="text-align: left"><!--CRLF--></p>
<pre style="text-align: left">INSERT <span style="color: #0000ff">INTO</span> ReadPastTest</pre>
<p style="text-align: left"><!--CRLF--></p>
<pre style="text-align: left"><span style="color: #0000ff"> VALUES</span> (1,<span style="color: #006080">'do a'</span>),(2,<span style="color: #006080">'do b'</span>),(3,<span style="color: #006080">'do c'</span>),(4,<span style="color: #006080">'do d'),</span><span style="color: #006080">(5,'do e')</span></pre>
<pre style="text-align: left"> GO</pre>
<pre style="text-align: left"><span style="color: #0000ff"> SELECT</span> CommandDescription</pre>
<p style="text-align: left"><!--CRLF--></p>
<pre style="text-align: left"><span style="color: #0000ff">FROM</span> ReadPastTest</pre>
<p style="text-align: left"><!--CRLF--></p>
<pre style="text-align: left">GO</pre>
<p><!--CRLF--></p>
</div>
</div>
<p dir="ltr"><strong><em>· Select the rows. </em></strong></p>
<p dir="ltr"><a href="http://www.madeira.co.il/wp-content/uploads/2012/01/11.jpg" rel="wp-prettyPhoto[g3890]"><img class="alignleft size-full wp-image-3897" src="http://www.madeira.co.il/wp-content/uploads/2012/01/11.jpg" alt="" width="147" height="135" /></a></p>
<p dir="ltr">
<p dir="ltr"><strong><em>· Open a new transaction and update one of the rows and keep the transaction open. </em></strong></p>
<div>
<div>
<pre style="text-align: left"><span style="color: #0000ff">BEGIN</span> <span style="color: #0000ff">TRANSACTION </span></pre>
<p style="text-align: left"><!--CRLF--></p>
<pre style="text-align: left"><span style="color: #0000ff">UPDATE</span> ReadPastTest</pre>
<p style="text-align: left"><!--CRLF--></p>
<pre style="text-align: left"><span style="color: #0000ff">SET</span> CommandId = 11</pre>
<p style="text-align: left"><!--CRLF--></p>
<pre style="text-align: left"><span style="color: #0000ff">WHERE</span> CommandId = 1</pre>
<p style="text-align: left"><!--CRLF--></p>
</div>
</div>
<p style="text-align: left">
<p dir="ltr"><em><strong>· Select the rows again with another query window that simulate a new process with the Readpast option. </strong></em></p>
<div>
<div>
<pre style="text-align: left"><span style="color: #0000ff">SELECT</span> CommandDescription</pre>
<p style="text-align: left"><!--CRLF--></p>
<pre style="text-align: left"><span style="color: #0000ff">(FROM</span> ReadPastTest <span style="color: #0000ff">WITH</span> (READPAST</pre>
<p style="text-align: left"><!--CRLF--></p>
<pre style="text-align: left">GO</pre>
</div>
</div>
<p dir="ltr"><em><strong>· Observe the changes. </strong></em></p>
<p dir="ltr"><a href="http://www.madeira.co.il/wp-content/uploads/2012/01/21.jpg" rel="wp-prettyPhoto[g3890]"><img class="alignleft size-full wp-image-3898" src="http://www.madeira.co.il/wp-content/uploads/2012/01/21.jpg" alt="" width="145" height="114" /></a></p>
<p dir="ltr"><em><strong>· Rollback the first transaction and select the table again.</strong></em></p>
<div>
<div>
<pre style="text-align: left"><span style="color: #0000ff">ROLLBACK</span></pre>
<p style="text-align: left"><!--CRLF--></p>
<pre style="text-align: left"><span style="color: #0000ff">SELECT</span> CommandDescription</pre>
<p style="text-align: left"><!--CRLF--></p>
<pre style="text-align: left"><span style="color: #0000ff">FROM</span> ReadPastTest</pre>
<p style="text-align: left"><!--CRLF--></p>
<pre style="text-align: left">GO</pre>
<p><!--CRLF--></p>
</div>
</div>
<p dir="ltr"><a href="http://www.madeira.co.il/wp-content/uploads/2012/01/12.jpg" rel="wp-prettyPhoto[g3890]"><img class="alignleft size-full wp-image-3899" src="http://www.madeira.co.il/wp-content/uploads/2012/01/12.jpg" alt="" width="147" height="135" /></a></p>
<p dir="ltr">
<p dir="ltr">As you can see at the first selection we get all five rows description and the second selection we get only four rows because one row is locked by the first transaction and it was skipped, at last the missing row returns after the rollback.</p>
<p dir="ltr"><strong>In conclusion:</strong></p>
<p dir="ltr">the Readpast option is suited to specific cases only, and can provides a perfect solution to those cases. It is important to beware not to use it on every deadlock or locks problems.</p>
</div>]]></content:encoded>			<wfw:commentRss>http://www.madeira.co.il/readpast-what-is-it-good-for/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>&#8235;Help The Optimizer&#8236;</title>		<link>http://www.madeira.co.il/help-the-optimizer-2/</link>
		<comments>http://www.madeira.co.il/help-the-optimizer-2/#comments</comments>
		<pubDate>Tue, 24 Jan 2012 10:05:42 +0000</pubDate>
		<dc:creator>&#8235;דודי רוזנטל&#8236;</dc:creator>				<category><![CDATA[כללי]]></category>
		<category><![CDATA[מאמרים]]></category>
		<category><![CDATA[מקודמות]]></category>
		<category><![CDATA[Execution Plan]]></category>
		<category><![CDATA[Optimizer]]></category>
		<category><![CDATA[SQL Server 2008 R2]]></category>

		<guid isPermaLink="false">http://www.madeira.co.il/?p=3833</guid>
		<description><![CDATA[&#8235;Even a smart tool with a complicated algorithm such as the optimizer might sometimes need our help. Help it and get helped even more!&#8236;]]></description>			<content:encoded><![CDATA[<div dir="rtl"><p><img src='http://www.madeira.co.il/wp-content/plugins/simple-post-thumbnails/timthumb.php?src=/wp-content/thumbnails/3833.jpg&amp;w=214&amp;h=129&amp;zc=1&amp;ft=jpg' alt='post thumbnail' /></p>
<p dir="ltr">Reading this posts title might make us smile: Me helping the optimizer? Isn’t it the one who supposes to help me?</p>
<p dir="ltr">Well, yes and no. The optimizer might help me getting the best execution pal for my queries (as long as I keep performing the right maintenance issues), but is some cases I can hint it to perform even better, and the way to do it is by re-scripting, re-quering and using nothing but some basic TSQL.</p>
<p dir="ltr">As always, an example shown might be worth a thousand words, and my purpose is to make my point with less than a half.</p>
<p dir="ltr">Lets take a look at a script of a procedure which job is to receive data of workers entering and exiting a factory and in addition to inserting it into a table, presenting it on screen for boarder guards:</p>
<p dir="ltr">
<p dir="ltr"><strong>SET ANSI_NULLS ON<br />
SET QUOTED_IDENTIFIER OFF<br />
GO</strong></p>
<p dir="ltr"><strong>CREATE PROCEDURE [dbo].[sp_TLA_Monitor]</strong></p>
<p dir="ltr"><strong>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;<br />
@pUserNo      int      ,<br />
@pSort        smallint ,<br />
@pDoor        int      ,<br />
@pFilterP     smallint = 0 ,<br />
@pFilterV     smallint = 0<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</strong></p>
<p dir="ltr"><strong>AS<br />
DECLARE @ActLinkString varchar(8000)<br />
SET nocount on </strong></p>
<p dir="ltr"><strong>SET @ActLinkString = &quot;</strong></p>
<p dir="ltr"><strong>IF @pFilterP &gt; 0 AND @pFilterP &lt; 4<br />
BEGIN<br />
SET @ActLinkString =<br />
'DECLARE @NUMERATOR int '+<br />
'SET @NUMERATOR = ( SELECT MIN( MA.Numerator ) '+<br />
' FROM TLA_OpenEvents MA  '+</strong></p>
<p dir="ltr"><strong>CASE WHEN ( @pFilterP = 1 ) THEN 'WHERE DATEDIFF( day   ,  EventTime , GETDATE() ) &lt; 1 ) '<br />
WHEN ( @pFilterP = 2 ) THEN 'WHERE DATEDIFF( Hour  ,  EventTime , GETDATE() ) &lt; '+CAST( @pFilterV  AS VARCHAR) +' ) '<br />
WHEN ( @pFilterP = 3 ) THEN 'WHERE DATEDIFF( day   ,  EventTime , GETDATE() ) &lt; '+CAST( @pFilterV  AS VARCHAR) +' ) '<br />
ELSE ' ' END<br />
END</strong></p>
<p dir="ltr"><strong>SET @ActLinkString = @ActLinkString +<br />
'SELECT C.Descript Controller , DE.Descript Device , '+<br />
'cObjCode =  CASE WHEN ISNULL( DO.Code , 0 ) &lt;&gt; 0 THEN DO.Code ELSE CASE WHEN ( MA.Type &gt;= 810 AND MA.Type &lt;= 817 )  THEN MA.ControllerPhisicalID  ELSE MA.Device END END , '+<br />
'cObjType =  CASE WHEN ISNULL( DO.Code , 0 ) &lt;&gt; 0 THEN 1100    ELSE CASE WHEN ( MA.Type &gt;= 810 AND MA.Type &lt;= 817 )  THEN 1200 ELSE 1300 END  END , DO.Descript Door , '+ </strong></p>
<p dir="ltr"><strong> 'MA.Badge Card , W.No WCNo, W.Name WC , DP.No DepNo, DP.Name Dep ,'+<br />
'OE.EventTime , ED.Descript Type ,'+<br />
'OE.FirstOperator ,'+<br />
'FirstOperatorDescr = (SELECT Emp_Name From Emp Where Emp_no = OE.FirstOperator ),'+<br />
'OE.FirstTreatEventTime , '+<br />
'OE.LastOperator  ,'+<br />
'LastOperatorDescr  = (SELECT Emp_Name From Emp Where Emp_no = OE.LastOperator  ),'+<br />
'OE.EndTime , '+<br />
'OE.Numerator , OE.Code , ED.Color , '+<br />
'OE.Severity , OE.Sensitivty ,OE.Priority , OE.Status , '+<br />
'UserType = ISNULL( vwObj.ObjType , 0 ) , '+<br />
'CarNo    = vwObj.ObjCarNo , '+<br />
'EmpNo    = vwObj.ObjNo    ,  Emp_Name = vwObj.ObjName , '+<br />
'xFunction = ( SELECT Descript FROM dvc_def WHERE code = MA.FunctionCode ) , '+<br />
'Pic =  vwObj.ObjPic '+</strong></p>
<p dir="ltr"><strong>'FROM TLA_Mov_Access MA '+<br />
'left join vw_ObjectType   vwObj  on vwObj.ObjCode  =  MA.Emp_no AND MA.Tag_Type = vwObj.ObjType '+<br />
'left join Work_c          W      on W.No           =  vwObj.ObjStation '+<br />
'left join Dep             DP     on DP.No          =  vwObj.ObjDep '+<br />
'join TLA_OpenEvents       OE     on OE.Numerator   =  MA.Numerator '+<br />
'left join TLA_Devices     DE     on DE.Code        =  MA.Device '+<br />
'join TLA_EventsDef        ED     on ED.Code        =  MA.Event '+<br />
'left join TLA_Doors       DO     on DO.Code        =  DE.Door '+<br />
'left join TLA_Controllers C      on C.Code         =  MA.ControllerPhisicalID '+<br />
' join dbo.fnc_GetMapPerm('+CAST( @pUserNo AS VARCHAR )+', 12 )  GMP on GMP.Control = ISNULL(DO.Code,-1) '+ &#8211;210609</strong></p>
<p dir="ltr"><strong> CASE WHEN ( @pFilterP = 0 ) THEN 'WHERE 1 = 1 '<br />
WHEN ( @pFilterP = 1 ) THEN 'WHERE MA.Numerator &gt; @NUMERATOR  '<br />
WHEN ( @pFilterP = 2 ) THEN 'WHERE MA.Numerator &gt; @NUMERATOR  '<br />
WHEN ( @pFilterP = 3 ) THEN 'WHERE MA.Numerator &gt; @NUMERATOR  '<br />
WHEN ( @pFilterP = 4 ) THEN 'WHERE MA.Numerator &gt; (SELECT MAX(Numerator) &#8211; '+CAST( @pFilterV  AS VARCHAR)+' FROM TLA_Mov_Access) ' ELSE 'WHERE 1 = 1' END +</strong></p>
<p dir="ltr"><strong> CASE WHEN ( @pDoor &gt;= 0 ) THEN ' AND DO.Code = '+CAST( @pDoor AS VARCHAR) ELSE ' ' END + </strong></p>
<p dir="ltr"><strong> CASE @pSort<br />
WHEN  0 THEN  ' ORDER BY OE.Numerator DESC '<br />
WHEN  1 THEN  ' ORDER BY OE.Priority DESC '<br />
WHEN  2 THEN  ' ORDER BY OE.Severity DESC '<br />
WHEN  3 THEN  ' ORDER BY OE.Sensitivty DESC ' END</strong></p>
<p dir="ltr"><strong>EXEC @ActLinkString</strong></p>
<p dir="ltr"><strong>GO<br />
SET QUOTED_IDENTIFIER OFF<br />
GO<br />
SET ANSI_NULLS ON<br />
GO</strong></p>
<p dir="ltr">
<p dir="ltr">As you can see, the procedure creates a string to be executed.</p>
<p dir="ltr">We noticed that recently query time of running this procedure is much longer than it used to be – a growth of hundreds of percents. Checking all maintenance issues (indexes, fragmentations etc.) didn’t help the query to run faster like it used to.</p>
<p dir="ltr">Then we ran the Execution Plan of the query and got this:</p>
<p dir="ltr"><a href="http://www.madeira.co.il/wp-content/uploads/2012/01/sp_TLA_Monitor_Before_Execution_Plan.png" rel="wp-prettyPhoto[g3833]"><img style="padding-left: 0px;padding-right: 0px;padding-top: 0px;border-width: 0px" src="http://www.madeira.co.il/wp-content/uploads/2012/01/sp_TLA_Monitor_Before_Execution_Plan_thumb.png" border="0" alt="sp_TLA_Monitor_Before_Execution_Plan" width="244" height="184" /></a></p>
<p dir="ltr">
<p dir="ltr">A kind of a complex one, as a query that uses lots of LEFT JOINs should look like.</p>
<p dir="ltr">Funny thing about it that when we looked at the details we saw in more than one place a huge difference between the estimated and the actual number of rows and between the estimated and the actual number of executions.</p>
<p dir="ltr"><a href="http://www.madeira.co.il/wp-content/uploads/2012/01/Key-Lookup.png" rel="wp-prettyPhoto[g3833]"><img style="padding-left: 0px;padding-right: 0px;padding-top: 0px;border-width: 0px" src="http://www.madeira.co.il/wp-content/uploads/2012/01/Key-Lookup_thumb.png" border="0" alt="Key Lookup" width="114" height="244" /></a></p>
<p dir="ltr">
<p dir="ltr">Checked again if statistics are updated. Well, they were.</p>
<p dir="ltr">So what is it? What makes the optimizer get the wrong impression? We assumed that if the estimated numbers were closer, much closer in fact, to the actual numbers, optimizer could have probably chosen a second way, different one and perhaps much better one, to execute the query.</p>
<p dir="ltr">Answer is simple: The more complex a query is, the more stages it goes along the way and the more JOINs, mostly of course LEFT JOINs it uses, makes the algorithm become much less accurate. Take for an example a 10% of a standard deviation of the optimizer in estimation at each level. and you got yourself one irrelevant Execution Plan.</p>
<p dir="ltr">So what’s the solution for this problem, you may ask.</p>
<p dir="ltr">A good thing to do would be trying to rescript the query in a way that the optimizer will go step-by-step and perform less complex simultaneous processes.</p>
<p dir="ltr">This query might work better if instead of using one SELECT Statement will all these JOINs, we will try to use temporary tables and devide the SELECT vertically instead of horizontally. In that way, optimizer will use much less JOINs per INSERT INTO and Execution Plan might be devided to more levels, but much more simple in each level.</p>
<p dir="ltr">It should be looking something like this:</p>
<p dir="ltr">
<p dir="ltr"><strong>SET ANSI_NULLS ON<br />
SET QUOTED_IDENTIFIER OFF<br />
GO</strong></p>
<p dir="ltr"><strong>CREATE PROCEDURE [dbo].[sp_TLA_Monitor_Test]</strong></p>
<p dir="ltr"><strong>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;<br />
@pUserNo      int      ,<br />
@pSort        smallint ,<br />
@pDoor        int      ,<br />
@pFilterP     smallint = 0 ,<br />
@pFilterV     smallint = 0<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</strong></p>
<p dir="ltr"><strong>/*<br />
DOOR       = 1100;<br />
CONTROLLER = 1200;<br />
DEVICE     = 1300;<br />
BUILDING   = 2000;<br />
IMAGE      = 3000;<br />
BUZZER     = 4000;<br />
*/</strong></p>
<p dir="ltr"><strong>AS<br />
DECLARE @ActLinkString varchar(8000)<br />
SET nocount on </strong></p>
<p dir="ltr"><strong>SET @ActLinkString = &quot;</strong></p>
<p dir="ltr"><strong>IF @pFilterP &gt; 0 AND @pFilterP &lt; 4<br />
BEGIN<br />
SET @ActLinkString =<br />
'DECLARE @NUMERATOR int '+<br />
'SET @NUMERATOR = ( SELECT MIN( MA.Numerator ) '+<br />
' FROM TLA_OpenEvents MA  '+</strong></p>
<p dir="ltr"><strong> CASE WHEN ( @pFilterP = 1 ) THEN 'WHERE DATEDIFF( day   ,  EventTime , GETDATE() ) &lt; 1 ) '<br />
WHEN ( @pFilterP = 2 ) THEN 'WHERE DATEDIFF( Hour  ,  EventTime , GETDATE() ) &lt; '+CAST( @pFilterV  AS VARCHAR) +' ) '<br />
WHEN ( @pFilterP = 3 ) THEN 'WHERE DATEDIFF( day   ,  EventTime , GETDATE() ) &lt; '+CAST( @pFilterV  AS VARCHAR) +' ) '<br />
ELSE ' ' END<br />
END</strong></p>
<p dir="ltr"><strong>SET @ActLinkString = @ActLinkString +<br />
'SELECT '+<br />
'MA.Badge Card, '+<br />
'MA.Tag_Type, '+<br />
'MA.Emp_no, '+<br />
'MA.Numerator Num1, '+<br />
'MA.Event, '+<br />
'MA.Device Dev1, '+<br />
'MA.ControllerPhisicalID, '+<br />
'MA.FunctionCode, '+<br />
'MA.Type Type1, '+<br />
'C.Descript Controller '+<br />
'INTO '+<br />
'#Tmp1 '+<br />
'FROM '+<br />
'TLA_Mov_Access MA '+<br />
'LEFT JOIN TLA_Controllers C on MA.ControllerPhisicalID=C.Code '+</strong></p>
<p><strong> </strong></p>
<div style="direction: ltr"><span style="font-weight: bold">'SELECT '+</span></div>
<p><strong> </strong></p>
<p><strong> </strong></p>
<p><strong> </strong></p>
<p><strong></p>
<div style="direction: ltr">'T.Card, T.Tag_Type, T.Emp_no, T.Num1, T.Event, T.Dev1, T.Controller, T.ControllerPhisicalID, T.FunctionCode, T.Type1, '+</div>
<div style="direction: ltr">'UserType = ISNULL(vwObj.ObjType, 0), '+</div>
<div style="direction: ltr">'CarNo    = vwObj.ObjCarNo, '+</div>
<div style="direction: ltr">'EmpNo    = vwObj.ObjNo, '+</div>
<div style="direction: ltr">'Emp_Name = vwObj.ObjName, '+</div>
<div style="direction: ltr">'Pic =  vwObj.ObjPic, '+</div>
<div style="direction: ltr">'vwObj.ObjStation, '+</div>
<div style="direction: ltr">'vwObj.ObjDep '+</div>
<div style="direction: ltr">'INTO '+</div>
<div style="direction: ltr">'#Tmp2 '+</div>
<div style="direction: ltr">'FROM '+</div>
<div style="direction: ltr">'#Tmp1 T '+</div>
<div style="direction: ltr">'LEFT JOIN vw_ObjectType vwObj on vwObj.ObjCode=T.Emp_no AND T.Tag_Type=vwObj.ObjType '+</div>
<p></strong></p>
<p><strong> </strong></p>
<p><strong> </strong></p>
<p><strong> </strong></p>
<p dir="ltr"><strong>'SELECT '+<br />
'T.Card, T.Tag_Type, T.Emp_no, T.Num1, T.Event, T.Dev1, T.Controller, T.ControllerPhisicalID, T.FunctionCode, T.Type1, '+<br />
'T.UserType, T.CarNo, T.EmpNo, T.Emp_Name, T.Pic, T.ObjStation, T.ObjDep, '+<br />
'OE.EventTime, '+<br />
'OE.FirstOperator,'+<br />
'FirstOperatorDescr = (SELECT Emp_Name From Emp Where T.Emp_no = OE.FirstOperator), '+<br />
'OE.FirstTreatEventTime, '+<br />
'OE.LastOperator, '+<br />
'LastOperatorDescr = (SELECT Emp_Name From Emp Where T.Emp_no = OE.LastOperator), '+<br />
'OE.EndTime, '+<br />
'OE.Numerator, '+<br />
'OE.Code, '+<br />
'OE.Severity, '+<br />
'OE.Sensitivty, '+<br />
'OE.Priority, '+<br />
'OE.Status, '+<br />
'ED.Descript Type, '+<br />
'ED.Color '+<br />
'INTO '+<br />
'#Tmp3 '+<br />
'FROM '+<br />
'#Tmp2 T '+<br />
'JOIN TLA_OpenEvents OE on OE.Numerator=T.Num1 '+<br />
'JOIN TLA_EventsDef ED on ED.Code=T.Event '+</strong></p>
<div style="direction: ltr"><span style="font-weight: bold">'SELECT '+</span></div>
<p><strong> </strong></p>
<p><strong> </strong></p>
<p><strong></p>
<div style="direction: ltr">'T.Card, T.Tag_Type, T.Emp_no, T.Num1, T.Event, T.Dev1, T.Controller, T.ControllerPhisicalID, T.FunctionCode, T.Type1, '+</div>
<div style="direction: ltr">'T.UserType, T.CarNo, T.EmpNo, T.Emp_Name, T.Pic, T.ObjStation, T.ObjDep, '+</div>
<div style="direction: ltr">'T.EventTime, T.FirstOperator, T.FirstOperatorDescr, T.FirstTreatEventTime, T.LastOperator, '+</div>
<div style="direction: ltr">'T.LastOperatorDescr, T.EndTime, T.Numerator, T.Code, T.Severity, T.Sensitivty, '+</div>
<div style="direction: ltr">'T.Priority, T.Status, T.Type, T.Color, '+</div>
<div style="direction: ltr">'DE.Descript Device, '+</div>
<div style="direction: ltr">'xFunction = (SELECT Descript FROM dvc_def WHERE code = T.FunctionCode), '+</div>
<div style="direction: ltr">'DO.Descript Door, '+</div>
<div style="direction: ltr">'cObjCode =  CASE WHEN ISNULL( DO.Code , 0 ) &lt;&gt; 0 THEN DO.Code ELSE CASE WHEN ( T.Type1 &gt;= 810 AND T.Type1 &lt;= 817 )  THEN T.ControllerPhisicalID  ELSE T.Dev1 END END , '+</div>
<div style="direction: ltr">'cObjType =  CASE WHEN ISNULL( DO.Code , 0 ) &lt;&gt; 0 THEN 1100    ELSE CASE WHEN ( T.Type1 &gt;= 810 AND T.Type1 &lt;= 817 )  THEN 1200 ELSE 1300 END  END '+</div>
<div style="direction: ltr">'INTO '+</div>
<div style="direction: ltr">'#Tmp4 '+</div>
<div style="direction: ltr">'FROM '+</div>
<div style="direction: ltr">'#Tmp3 T '+</div>
<div style="direction: ltr">'LEFT JOIN TLA_Devices DE on T.Dev1=DE.Code '+</div>
<div style="direction: ltr">'LEFT JOIN TLA_Doors DO on DE.Door=DO.Code '+</div>
<div style="direction: ltr">'JOIN dbo.fnc_GetMapPerm('+CAST( @pUserNo AS VARCHAR )+', 12 )  GMP on GMP.Control = ISNULL(DO.Code,-1) '+</div>
<p></strong></p>
<p><strong> </strong></p>
<p><strong> </strong></p>
<p><strong> </strong></p>
<p><strong> </strong></p>
<div style="direction: ltr"><span style="font-weight: bold">'SELECT '+</span></div>
<p><strong> </strong></p>
<p><strong> </strong></p>
<p><strong></p>
<div style="direction: ltr">'T.Controller, '+</div>
<div style="direction: ltr">'T.Device, '+</div>
<div style="direction: ltr">'T.cObjCode, '+</div>
<div style="direction: ltr">'T.cObjType, '+</div>
<div style="direction: ltr">'T.Door, '+</div>
<div style="direction: ltr">'T.Card, '+</div>
<div style="direction: ltr">'W.No WCNo, '+</div>
<div style="direction: ltr">'W.Name WC, '+</div>
<div style="direction: ltr">'DP.No DepNo, '+</div>
<div style="direction: ltr">'DP.Name Dep, '+</div>
<div style="direction: ltr">'T.EventTime, '+</div>
<div style="direction: ltr">'T.Type, '+</div>
<div style="direction: ltr">'T.FirstOperator, '+</div>
<div style="direction: ltr">'T.FirstOperatorDescr, '+</div>
<div style="direction: ltr">'T.FirstTreatEventTime, '+</div>
<div style="direction: ltr">'T.LastOperator, '+</div>
<div style="direction: ltr">'T.LastOperatorDescr, '+</div>
<div style="direction: ltr">'T.EndTime, '+</div>
<div style="direction: ltr">'T.Numerator, '+</div>
<div style="direction: ltr">'T.Code, '+</div>
<div style="direction: ltr">'T.Color, '+</div>
<div style="direction: ltr">'T.Severity, '+</div>
<div style="direction: ltr">'T.Sensitivty, '+</div>
<div style="direction: ltr">'T.Priority, '+</div>
<div style="direction: ltr">'T.Status, '+</div>
<div style="direction: ltr">'T.UserType, '+</div>
<div style="direction: ltr">'T.CarNo, '+</div>
<div style="direction: ltr">'T.EmpNo, '+</div>
<div style="direction: ltr">'T.Emp_Name, '+</div>
<div style="direction: ltr">'T.xFunction, '+</div>
<div style="direction: ltr">'T.Pic '+</div>
<div style="direction: ltr">'FROM '+</div>
<div style="direction: ltr">'#Tmp4 T '+</div>
<div style="direction: ltr">'LEFT JOIN Work_c W on T.ObjStation=W.No '+</div>
<div style="direction: ltr">'LEFT JOIN Dep DP on T.ObjDep=DP.No '+</div>
<p></strong></p>
<p><strong> </strong></p>
<p><strong> </strong></p>
<p dir="ltr"><strong> CASE WHEN ( @pFilterP = 0 ) THEN 'WHERE 1 = 1 '<br />
WHEN ( @pFilterP = 1 ) THEN 'WHERE T.Numerator &gt; @NUMERATOR  '<br />
WHEN ( @pFilterP = 2 ) THEN 'WHERE T.Numerator &gt; @NUMERATOR  '<br />
WHEN ( @pFilterP = 3 ) THEN 'WHERE T.Numerator &gt; @NUMERATOR  '<br />
WHEN ( @pFilterP = 4 ) THEN 'WHERE T.Numerator &gt; (SELECT MAX(Numerator) &#8211; '+CAST( @pFilterV  AS VARCHAR)+' FROM TLA_Mov_Access) ' ELSE 'WHERE 1 = 1' END +</strong></p>
<p dir="ltr"><strong> CASE WHEN ( @pDoor &gt;= 0 ) THEN ' AND T.Code = '+CAST( @pDoor AS VARCHAR) ELSE ' ' END + </strong></p>
<p dir="ltr"><strong> CASE @pSort<br />
WHEN  0 THEN  ' ORDER BY T.Numerator DESC '<br />
WHEN  1 THEN  ' ORDER BY T.Priority DESC '<br />
WHEN  2 THEN  ' ORDER BY T.Severity DESC '<br />
WHEN  3 THEN  ' ORDER BY T.Sensitivty DESC ' END</strong></p>
<p dir="ltr"><strong>EXECUTE(@ActLinkString)</strong></p>
<p dir="ltr"><strong>GO<br />
SET QUOTED_IDENTIFIER OFF<br />
GO<br />
SET ANSI_NULLS ON<br />
GO</strong></p>
<p dir="ltr">
<p dir="ltr">And the Execution Plan of it will look something like this:</p>
<p dir="ltr"><a href="http://www.madeira.co.il/wp-content/uploads/2012/01/sp_TLA_Monitor_After_Execution_Plan.png" rel="wp-prettyPhoto[g3833]"><img style="padding-left: 0px;padding-right: 0px;padding-top: 0px;border-width: 0px" src="http://www.madeira.co.il/wp-content/uploads/2012/01/sp_TLA_Monitor_After_Execution_Plan_thumb.png" border="0" alt="sp_TLA_Monitor_After_Execution_Plan" width="244" height="184" /></a></p>
<p dir="ltr">
<p dir="ltr">Try it. You will be surprised to find out how many times it helps queries to be executed much faster. Where it looks like there’s no hope, this solution just might be the one!</p>
</div>]]></content:encoded>			<wfw:commentRss>http://www.madeira.co.il/help-the-optimizer-2/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>&#8235;SQL Azure &#8211; What is it ?&#8236;</title>		<link>http://www.madeira.co.il/sql-azure-what-is-it/</link>
		<comments>http://www.madeira.co.il/sql-azure-what-is-it/#comments</comments>
		<pubDate>Fri, 20 Jan 2012 16:14:01 +0000</pubDate>
		<dc:creator>&#8235;שאוליאן חן&#8236;</dc:creator>				<category><![CDATA[בלוגים]]></category>
		<category><![CDATA[כללי]]></category>
		<category><![CDATA[מקודמות]]></category>
		<category><![CDATA[SQL Azure]]></category>

		<guid isPermaLink="false">http://www.madeira.co.il/?p=3789</guid>
		<description><![CDATA[&#8235;So everyone is talking about the next big thing … but what is really the SQL Azure.

SQL Azure provides cloud services to databases that allow you to focus on implementation, rather than build, manage and maintain databases.
This means that you no longer need to deal with installing servers, install the SQL, keep big hard disks, servers and so on … all you need to start working you get from Microsoft and now all that's left to you is to focus on developing.&#8236;]]></description>			<content:encoded><![CDATA[<div dir="rtl"><p><img src='http://www.madeira.co.il/wp-content/plugins/simple-post-thumbnails/timthumb.php?src=/wp-content/thumbnails/3789.jpg&amp;w=214&amp;h=129&amp;zc=1&amp;ft=jpg' alt='post thumbnail' /></p>
<p dir="ltr">So everyone is talking about the next big thing … but what is really the SQL Azure.</p>
<p dir="ltr">SQL Azure provides cloud services to databases that allow you to focus on implementation, rather than build, manage and maintain databases. This means that you no longer need to deal with installing servers, install the SQL, keep big hard disks, servers and so on … all you need to start working you get from Microsoft and now all that's left to you is to focus on developing.</p>
<p dir="ltr">The SQL Azure is part of big family that Microsoft launched on the cloud together with Windows Azure, .NET Services and more.</p>
<p dir="ltr">You can connect to SQL in two ways:</p>
<p dir="ltr">1. By the way we all know and love, through the SSMS.</p>
<p dir="ltr">fiil in the Server name : [server].database.windows.net</p>
<p dir="ltr"><a href="http://www.madeira.co.il/wp-content/uploads/2012/01/sql-connction1.jpg" rel="wp-prettyPhoto[g3789]"><img style="padding-left: 0px;padding-right: 0px;padding-top: 0px;border-width: 0px" src="http://www.madeira.co.il/wp-content/uploads/2012/01/sql-connction_thumb.jpg" border="0" alt="sql connction" width="362" height="275" /></a></p>
<p dir="ltr">2. Via the SQL Azure portal &#8230; which I will expand in another post.</p>
<p dir="ltr"><a href="http://www.madeira.co.il/wp-content/uploads/2012/01/azure-portal1.jpg" rel="wp-prettyPhoto[g3789]"><img style="padding-left: 0px;padding-right: 0px;padding-top: 0px;border-width: 0px" src="http://www.madeira.co.il/wp-content/uploads/2012/01/azure-portal_thumb.jpg" border="0" alt="" width="455" height="245" /></a></p>
<p dir="ltr">So let's talk about two important things … we'll start with the price … The payment is only for what you used, when the costs in relation to ownership or hosting on servers, are significantly lower. And the cost is measured in dollars alone per day. The cost is divided into two parts:<br />
1. Payment for the Database</p>
<p dir="ltr">There are two types of editions that you can purchase web edition and business edition:</p>
<p dir="ltr">Web Edition</p>
<p dir="ltr">$9.99 per database up to 1GB per month</p>
<p dir="ltr">$49.95 per database up to 5GB per month</p>
<p dir="ltr">Business Edition</p>
<p dir="ltr">$99.99 per database up to 10GB per month</p>
<p dir="ltr">$199.98 per database up to 20GB per month</p>
<p dir="ltr">$299.97 per database up to 30GB per month</p>
<p dir="ltr">$399.96 per database up to 40GB per month</p>
<p dir="ltr">$499.95 per database up to 50GB per month</p>
<p dir="ltr">for 100GB and 150GB per month, according to reports from Microsoft, the price shall not exceed more than $499.95.</p>
<p dir="ltr">2. Payments for the Traffic to and from the database, when the Traffic in the cloud there is not charge.</p>
<p dir="ltr">To get the cost for the data transfer you can use the following script:</p>
<div style="text-align: left;padding: 4px;line-height: 12pt;background-color: #f4f4f4;margin: 20px 0px 10px;width: 97.5%;font-family: 'Courier New',courier,monospace;direction: ltr;font-size: 8pt;overflow: auto;cursor: text;border: 1px solid silver">
<div style="border-style: none;text-align: left;padding: 0px;line-height: 12pt;background-color: #f4f4f4;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible">
<pre style="border-style: none;text-align: left;padding: 0px;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible"><span style="color: #606060">   1:</span> <span style="color: #0000ff">DECLARE</span> @cost_per_mb <span style="color: #0000ff">DECIMAL</span> (3,2)=0.15</pre>
<p><!--CRLF--></p>
<pre style="border-style: none;text-align: left;padding: 0px;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible"><span style="color: #606060">   2:</span> <span style="color: #0000ff">DECLARE</span> @mb <span style="color: #0000ff">INT</span> = 1024*1024;</pre>
<p><!--CRLF--></p>
<pre style="border-style: none;text-align: left;padding: 0px;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible"><span style="color: #606060">   3:</span></pre>
<p><!--CRLF--></p>
<pre style="border-style: none;text-align: left;padding: 0px;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible"><span style="color: #606060">   4:</span> <span style="color: #0000ff">SELECT</span></pre>
<p><!--CRLF--></p>
<pre style="border-style: none;text-align: left;padding: 0px;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible"><span style="color: #606060">   5:</span> u.Time_Period,</pre>
<p><!--CRLF--></p>
<pre style="border-style: none;text-align: left;padding: 0px;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible"><span style="color: #606060">   6:</span> u.Direction,</pre>
<p><!--CRLF--></p>
<pre style="border-style: none;text-align: left;padding: 0px;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible"><span style="color: #606060">   7:</span> @cost_per_mb * u.BandwidthInKB/@mb <span style="color: #0000ff">AS</span> [TotalTransferCost]</pre>
<p><!--CRLF--></p>
<pre style="border-style: none;text-align: left;padding: 0px;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible"><span style="color: #606060">   8:</span> <span style="color: #0000ff">FROM</span> (</pre>
<p><!--CRLF--></p>
<pre style="border-style: none;text-align: left;padding: 0px;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible"><span style="color: #606060">   9:</span>         <span style="color: #0000ff">SELECT</span></pre>
<p><!--CRLF--></p>
<pre style="border-style: none;text-align: left;padding: 0px;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible"><span style="color: #606060">  10:</span>         Time_Period,</pre>
<p><!--CRLF--></p>
<pre style="border-style: none;text-align: left;padding: 0px;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible"><span style="color: #606060">  11:</span>         Direction,</pre>
<p><!--CRLF--></p>
<pre style="border-style: none;text-align: left;padding: 0px;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible"><span style="color: #606060">  12:</span>         <span style="color: #ff33cc">SUM</span>(Quantity) <span style="color: #0000ff">AS</span> [BandwidthInKB]</pre>
<p><!--CRLF--></p>
<pre style="border-style: none;text-align: left;padding: 0px;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible"><span style="color: #606060">  13:</span>         <span style="color: #0000ff">FROM</span> sys.Bandwidth_Usage u</pre>
<p><!--CRLF--></p>
<pre style="border-style: none;text-align: left;padding: 0px;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible"><span style="color: #606060">  14:</span>         <span style="color: #0000ff">WHERE</span></pre>
<p><!--CRLF--></p>
<pre style="border-style: none;text-align: left;padding: 0px;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible"><span style="color: #606060">  15:</span>         u.<span style="color: #0000ff">TIME</span> &gt;=<span style="color: #ff33cc">DATEADD</span>(D,0-<span style="color: #ff33cc">DAY</span>(<span style="color: #ff33cc">GetUTCDate</span>()),GetUTCDate())</pre>
<p><!--CRLF--></p>
<pre style="border-style: none;text-align: left;padding: 0px;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible"><span style="color: #606060">  16:</span>         <span style="color: #888888">AND </span>u.<span style="color: #0000ff">TIME</span> &lt;=EOMONTH(<span style="color: #ff33cc">GetUTCDate</span>())</pre>
<p><!--CRLF--></p>
<pre style="border-style: none;text-align: left;padding: 0px;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible"><span style="color: #606060">  17:</span>         <span style="color: #888888">AND </span><span style="color: #000000">class </span>= <span style="color: #ff0000">'External'</span></pre>
<p><!--CRLF--></p>
<pre style="border-style: none;text-align: left;padding: 0px;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible"><span style="color: #606060">  18:</span>         <span style="color: #888888">AND </span>u.Direction = <span style="color: #ff0000">'Egress'</span></pre>
<p><!--CRLF--></p>
<pre style="border-style: none;text-align: left;padding: 0px;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible"><span style="color: #606060">  19:</span>         <span style="color: #0000ff">GROUP</span> <span style="color: #0000ff">BY</span> Time_Period, Direction</pre>
<p><!--CRLF--></p>
<pre style="border-style: none;text-align: left;padding: 0px;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible"><span style="color: #606060">  20:</span>      ) <span style="color: #0000ff">AS</span> u;</pre>
<p><!--CRLF--></p>
</div>
</div>
<p dir="ltr">Well, as you already know, you pay for the size of your database, and you pay for the data transfer. To be cost efficient, you really need to design your database correct to avoid redundant data and you need to stop using SELECT *, or including more columns than you need. Otherwise you’ll pay for an overhead that you actually can avoid.</p>
<p dir="ltr">After we understood the price, let's talk a little about the Availability high that Microsoft is so proud of her&#8230;</p>
<p dir="ltr">Microsoft promises 99.9% of Accessibility and Availability! And for that When you create a Database, in the background created three copies of your DB on different physical server (not virtual) to prevent data loss if a server falls. One replication is called PRIMARY and the others called SECONDARY, the reads and writes replicated the main base and are delivered in a-synchronic to the others, the secondary, if one replication falls another one rises immediately. The information is considered COMMITED only after the data is written to the primary disk (the transaction log reported that the data is written to the disk) and at least to one of the secondary.</p>
<p dir="ltr">That’s it for this time … hope I helped you educate a little bit <img class="wlEmoticon wlEmoticon-smile" style="border-style: none" src="http://www.madeira.co.il/wp-content/uploads/2012/01/wlEmoticon-smile.png" alt="סמיילי" /></p>
</div>]]></content:encoded>			<wfw:commentRss>http://www.madeira.co.il/sql-azure-what-is-it/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>&#8235;Update Statistics and the new TraceFlag 2371&#8236;</title>		<link>http://www.madeira.co.il/update-statistics-re-compilations-and-traceflag-2371/</link>
		<comments>http://www.madeira.co.il/update-statistics-re-compilations-and-traceflag-2371/#comments</comments>
		<pubDate>Wed, 18 Jan 2012 23:11:06 +0000</pubDate>
		<dc:creator>&#8235;נעם ברזיס&#8236;</dc:creator>				<category><![CDATA[בלוגים]]></category>
		<category><![CDATA[כללי]]></category>
		<category><![CDATA[מקודמות]]></category>

		<guid isPermaLink="false">http://www.madeira.co.il/?p=3748</guid>
		<description><![CDATA[&#8235;The new TraceFlag 2371 can be very effective if you have large tables, come and read all about it.&#8236;]]></description>			<content:encoded><![CDATA[<div dir="rtl"><p><img src='http://www.madeira.co.il/wp-content/plugins/simple-post-thumbnails/timthumb.php?src=/wp-content/thumbnails/3748.gif&amp;w=214&amp;h=129&amp;zc=1&amp;ft=jpg' alt='post thumbnail' /></p>
<p dir="ltr">What comes first &#8211; The Chicken or the Egg? What happens first – Update Statistics or Re-Compilations ?</p>
<h3 dir="ltr">The Statistics life cycle</h3>
<p dir="ltr">As a regular process of our DB life, data in our tables changes and hence statistics become less accurate. After a certain amount of changes (which I will discuss later in this post), SQL Server marks statistics to be non-valid.</p>
<p dir="ltr">This process marks the statistics as non-valid but doesn’t actually update them. Only when a query is compiled will SQL Server update the relevant statistics (if auto update statistics is on of course). After the statistics are updated, all the queries that rely on these statistics will be marked for re-compilation.</p>
<p dir="ltr">So actually the process is: </p>
<p dir="ltr">1. Many Changes (updates/ inserts/deletes) –&gt; Causes Non Valid Statistics </p>
<p dir="ltr">2. Query Compilation (happens Independently) –&gt; Causes Update Statistics –&gt; Causes All related queries to be re-compiled</p>
<p dir="ltr">&#160;</p>
<h3 dir="ltr">When are Statistics marked as non-valid</h3>
<p dir="ltr">After how many changes to the table are Statistics marked as non-valid?</p>
<p dir="ltr">After running the following <a href="http://www.madeira.co.il/wp-content/uploads/2012/01/AmountOfChangesForStatsAutoUpdate.sql" target="_blank">Script</a> you’ll find out that SQL Server marks statistics as non-valid if more than 20% of the rows were changed (counting changes only on columns related to the statistics).</p>
<p dir="ltr">&#160;</p>
<h3 dir="ltr">Trace Flag 2371</h3>
<p dir="ltr">20% of row changes sounds crazy high if the table has a lot of rows !</p>
<p dir="ltr">Consider for instance, a table containing data from the past 7 years. It would demand to wait a whole <b><u>1.4 year</u></b> of new data to have the statistics updated ! (assuming only inserts are done and same amount of inserts per year). So if you don’t update your statistics manually and have very large tables, you should have a close look at Trace Flag 2371. It actually changes the 20% threshold to be smaller according to the amount of rows in the table. The following chart shows the new thresholds:</p>
<p dir="ltr"><img src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-84-42-metablogapi/4370.clip_5F00_image002_5F00_thumb_5F00_64787B84.png" width="487" height="304" /></p>
<p dir="ltr">&#160;</p>
<p dir="ltr">The new Trace Flag is currently available on SQL Server 2008 R2 SP1 and on SQL Server 2012.</p>
<p dir="ltr">&#160;</p>
<p dir="ltr">I recommend reading 2 very interesting posts on Update Statistics:</p>
<p dir="ltr">1. <a href="http://sqlskills.com/BLOGS/KIMBERLY/category/Statistics.aspx" target="_blank">Filtered indexes and filtered stats might become seriously out-of-date</a> (<a href="http://www.sqlskills.com/blogs/Kimberly">Kimberly L. Tripp</a>)</p>
<p dir="ltr">2. <a href="http://blogs.msdn.com/b/saponsqlserver/archive/2011/09/07/changes-to-automatic-update-statistics-in-sql-server-traceflag-2371.aspx" target="_blank">Changes to automatic update statistics in SQL Server – traceflag 2371</a> (Juergen Thomas)</p>
</div>]]></content:encoded>			<wfw:commentRss>http://www.madeira.co.il/update-statistics-re-compilations-and-traceflag-2371/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>&#8235;NOLOCK&#8236;</title>		<link>http://www.madeira.co.il/nolock/</link>
		<comments>http://www.madeira.co.il/nolock/#comments</comments>
		<pubDate>Tue, 17 Jan 2012 00:15:08 +0000</pubDate>
		<dc:creator>&#8235;יוסי חקיקת&#8236;</dc:creator>				<category><![CDATA[כללי]]></category>

		<guid isPermaLink="false">http://www.madeira.co.il/?p=3719</guid>
		<description><![CDATA[&#8235;השימוש ב- NOLCK הפך בארגונים רבים להרגל. לטעמי זה הרגל מגונה. NOLOCK אכן תורם לביצועי המערכת ופותר כליל בעיות הקשורות לנעילות, אך לעיתים הוא יכול לגבות מחיר יקר על השימוש בו. לקבלת מידע מקיף כנסו למאמר....&#8236;]]></description>			<content:encoded><![CDATA[<div dir="rtl"><p><img src='http://www.madeira.co.il/wp-content/plugins/simple-post-thumbnails/timthumb.php?src=/wp-content/thumbnails/3719.png&amp;w=214&amp;h=129&amp;zc=1&amp;ft=jpg' alt='post thumbnail' /></p>
<p>היו הייתה עיר בשם חלם. חכמי העיר נתקלו באתגר לא פשוט, באחד הגשרים המרכזיים בעיר נפער חור, ורבים מתושבי העיר נפלו מן הגשר ונפצעו. נתכנסו כל חכמי העיר לטכס עצה, אחד מן החכמים שמע על פתרון שיושם בעיר השכנה, וחשב לתומו להעתיק אותו לעיר חלם. הפתרון היה הקמת בית חולים לטיפול בפצועיי הנפילות מהגשר. הדילמה עכשיו הייתה היכן למקם את בית החולים, חשבו וחשבו והגיעו למסקנה שיש למקם את בית החולים בדיוק מתחת לבור שיש בגשר, ככה החולים ייפלו ישר על גג בית החולים ויובהלו לקבלת טיפול רפואי. וכך יצא שהפתרון המזהיר של חכמי העיר למעשה לא הביא לשיפור המצב, ואף גרם להרעה במצב.</p>
<p>הסיפור הנ&quot;ל ממחיש לטעמי בצורה טובה למדיי את כל הקשור לשימוש ב- Locking Hint הנקרא: NOLOCK. ישנה בעיה, בד&quot;כ קשורה לנעילות, ומצד שני ישנו פתרון (NOLOCK) אבל במקרים לא מעטים זה לא הפתרון האמיתי לבעיה אלא פשוט הפתרון הקל. בארגונים רבים ישנו נוהל או מנהג להוסיף לכל שאילתה NOLOCK, בצורה אוטומטית בלי שום קשר לתוכן השליפה וללא מתן תשומת לב לשאלה החשובה כל כך, האם המידע שאני שולף הוא עדכני, תקף ולא עבר שום שינוי בזמן שליפתו! בד&quot;כ הסיבה לשימוש מאסיבי ב- NOLOCK היא זהה במרבית הארגונים, בשלב מסוים, הייתה בעיה של נעילות במערכת שגרמו לעיכובים וכמובן פגעו ישירות בביצועי המערכת, ואז מישהו עלה על הפתרון האולטימטיבי, גם אין נעילות וגם משפרים ביצועים תענוג נכון?? מצטער לקלקל לכם, אבל ממש לא!</p>
<p><span style="text-decoration: underline">ישנן מספר נקודות בסיסיות שעלינו להבין בנוגע לשימוש ב</span><span style="text-decoration: underline">-</span><span style="text-decoration: underline"> </span><span style="text-decoration: underline">NOLOCK</span><span style="text-decoration: underline">:</span></p>
<p>1. <strong>Allow Dirty Reads</strong>- כאשר מריצים פקודת SELECT עם NOLOCK המשמעות היא שאין שום השפעה לנעילות אחרות, כלומר יכול בהחלט להיווצר מצב שאנו קוראים שורות שבינתיים עשו עליהן ROLLBACK או מצד שני שורות שעדיין לא קיבלו COMMIT. (הערה: NOLOCK עובד בדיוק כמו Read Uncommitted, רק ש-Read Uncommitted מוגדר ברמת ה-Session).</p>
<p>2. <strong>לא גורם לנעילות ולא מתחשב בנעילות</strong>- וזו בעצם הסיבה שהשימוש ב-NOLOCK משפר את ביצועי המערכת. מחד גיסא הוא איננו מחזיק שום נעילה בעצמו. ומאידך גיסא, הוא איננו מכבד/מתחשב בשום נעילה אפילו לא בנעילה החזקה ביותר<span style="color: #ff0000"> <a href="http://msdn.microsoft.com/en-us/library/ms175519.aspx" target="_blank"><span style="color: #0000ff">Exclusive Lock</span></a></span>.</p>
<p>3. <strong>רשומות כפולות או היעדר רשומות</strong> &#8211; את הנקודה החשובה והמעניינת הזו לימד אותי <a href="http://www.madeira.co.il/author/noambresiz/" target="_blank"><span style="color: #0000ff">נעם ברזיס</span></a>. כאשר מרצים שאילתה שגורמת לפעולת Index Scan, יכול להיווצר שבו השימוש ב- NOLOCK יגרום ל-SQL Server לא להציג רשומה מסוימת או יציג אותה פעמיים (בלי שום קשר ל- Dirty Reads). לדוגמא:</p>
<p>משתמש הריץ את השאילתה הבאה, (הטבלה בעלת מספר גדול של רשומות) לטבלה יש אינדקס על עמודת Price:</p>
<div style="text-align: left"><span style="color: #0000ff">SELECT</span></div>
<div style="text-align: left">ProductName, Price, Orders</div>
<div style="text-align: left"><span style="color: #0000ff">FROM</span></div>
<div style="text-align: left">Table1</div>
<div style="text-align: left"><span style="color: #0000ff">WHERE</span></div>
<div style="text-align: left">Price BETWEEN 10.00 AND 20.00</div>
<p>לאחר 5 שניות ריצה לדוגמא, פעולת  ה- Index Scan הגיעה לערך 15.00 (יש לזכור שהסקירה מתבצעת לפי סדר האינדקס), משתמש אחר ב- Session אחר כמובן, ביצע פעולת INSERT שה- Price הוא 14.00. במצב זה, הרשומה שזה עתה נכנסה, לא תוצג ב- Record Set . משום שפעולת ה- Index Scan דילגה עליו.</p>
<p>אז לפני שאנו מוציאים נוהל חדש בארגון שמחייב להשתמש ב- NOLOCK באופן קבוע, בואו ננסה להבין ממה יכולות להיגרם נעילות רבות (על שלל סוגיהן):</p>
<p>· <strong>שימוש לא יעיל ב- </strong><strong>Transactions</strong><strong>-</strong> <strong>Transactions </strong>צריכות להישמר קצרות ככל הניתן! לשם המחשה, נגיד שיש לנו פרוצדורה ארוכה שבהתחלה מריצים בה פקודת SELECT דיי כבדה, שמכניסה את הנתונים לטבלה זמנית, לאחר מכן, מבצעים חישוב על אותם נתונים, עושים JOIN עם טבלה אחרת ואז בסוף כל זה יש פקודת UPDATE או DELETE. במצב כזה, יש לפתוח את ה- Transaction רק בפקודת ה-UPDATE או ה- DELETE ולא לאורך כל הפרוצדורה ולסגור אותה מיד בסיום הפעולה!</p>
<p>· <strong>תכנון לקוי</strong>- לעיתים הבעיה נעוצה בסדר הלוגי של הפעולות בתהליך מסוים. יש לנתח ולהבין מה קורה בכל שלב, לנסות לעלות על המצבים בהם יש נעילות שונות. ורק לאחר שמבינים היכן ולמה יש נעילות, לקבל החלטות.</p>
<p>· <strong>Foreign Keys</strong> – יכולים לגרום לנעילות במקרים מסוימים אבל נושא לפוסט שלם.</p>
<p><span style="text-decoration: underline">מתי נשתמש ב- </span><span style="text-decoration: underline">NOLOCK</span><span style="text-decoration: underline"> ומתי לא:</span></p>
<p>כלל ברזל- אם המידע שאנו שולפים צריך להיות מדויק ואמין וללא חשש שהוא השתנה בזמן ששלפנו אותו אז לעולם לא נשתמש ב- NOLOCK. לדוגמא, דוחות שקשורים לכספים וחיובים של לקוחות או גביית כסף, לעולם לא נפיק אותם עם NOLOCK (זו רק דוגמא להמחשה ישנם עוד מקרים רבים אחרים).לעומת זאת, לעיתים תכופות מריצים שאילתות שונות כלליות מאד כדי לקבל תמונת מצב ראשונית על מבנה של טבלאות ועל הנתונים שיש בהן, בדיקות כאלו לרוב לא מחייבות שהמידע יהיה עקבי לאותה שנייה שבא קראנו אותו. יתר על כן, לעיתים ישנם דוחות שמטרתם להציג אומדן ולא נתונים מדויקים, גם במקרים כאלו אין חשש להשתמש ב-NOLOCK.</p>
<p>לסיכום, כמו בהרבה תחומים אחרים ב- SQL Server אנחנו במצב מתמיד של שמיכה קצרה. שמתם NOLOCK הרווחתם ביצועים אבל להבין שיש מחיר לכך, אין ארוחות חינם, נכון, הרווחנו ביצועים, אבל הפסדנו דבר חשוב לא פחות והוא עקביות ואמינות המידע. אז בפעם הבאה שאתם מוסיפים NOLOCK, תעצרו לשנייה ותחשבו על ההשלכות לחיוב ושלילה ותקבלו החלטה מושכלת ומתוך מודעות.</p>
<p>חקיקת יוסי</p>
</div>]]></content:encoded>			<wfw:commentRss>http://www.madeira.co.il/nolock/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>&#8235;How are VLFs created, truncated and deleted?&#8236;</title>		<link>http://www.madeira.co.il/how-are-vlfs-created-truncated-and-deleted/</link>
		<comments>http://www.madeira.co.il/how-are-vlfs-created-truncated-and-deleted/#comments</comments>
		<pubDate>Mon, 16 Jan 2012 18:14:28 +0000</pubDate>
		<dc:creator>&#8235;Shay Attiya&#8236;</dc:creator>				<category><![CDATA[בלוגים]]></category>
		<category><![CDATA[מקודמות]]></category>
		<category><![CDATA[auto truncate]]></category>
		<category><![CDATA[Log file]]></category>
		<category><![CDATA[VLF]]></category>

		<guid isPermaLink="false">http://www.madeira.co.il/?p=3644</guid>
		<description><![CDATA[&#8235; Virtual Log Files or VLFs in short are the physical files that implement the log file. Here’s how they are created, truncated and deleted, and how we as DBAs can control it.&#8236;]]></description>			<content:encoded><![CDATA[<div dir="rtl"><p><img src='http://www.madeira.co.il/wp-content/plugins/simple-post-thumbnails/timthumb.php?src=/wp-content/thumbnails/3644.jpg&amp;w=214&amp;h=129&amp;zc=1&amp;ft=jpg' alt='post thumbnail' /></p>
<p dir="ltr">Today I chose to talk about Virtual Log Files or VLF in short. VLFs are the physical files that implement the log file. The log file’s log records are stored sequentially in a set of these physical files.</p>
<p dir="ltr"><strong>Creating a VLF:</strong></p>
<p dir="ltr">Every time space is allocated for the log file (Initial creation or log growth) new VLFs are created behind the scenes. The number of new VLFs is determined by the amount of space allocated.</p>
<p dir="ltr">1) 0MB &gt; Space Added &gt;= 64MB ,  4 new VLFs</p>
<p dir="ltr">2) 64MB &gt; Space Added &gt;= 1GB ,  8 new VLFs</p>
<p dir="ltr">3) 1GB &gt; Space Added,                 16 new VLFs</p>
<p dir="ltr">To demonstrate, I’ll use this script to create a DB with a log file in various sizes and auto growths. The database’s data file sizes is irrelevant.</p>
<div style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 20px 0px 10px;width: 97.5%;font-family: 'Courier New', courier, monospace;direction: ltr;font-size: 8pt;overflow: auto;cursor: text;border: silver 1px solid;padding: 4px">
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New', courier, monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #0000ff">USE</span>
    master;
<span style="color: #0000ff">GO</span>

<span style="color: #0000ff">IF</span> DB_ID(<span style="color: #006080">'MyDB'</span>) <span style="color: #0000ff">IS</span> <span style="color: #0000ff">NOT</span> <span style="color: #0000ff">NULL</span>
<span style="color: #0000ff">BEGIN</span>
    <span style="color: #0000ff">DROP</span> <span style="color: #0000ff">DATABASE</span> MyDB;
<span style="color: #0000ff">END</span>;

<span style="color: #0000ff">CREATE</span> <span style="color: #0000ff">DATABASE</span> MyDB
<span style="color: #0000ff">ON</span> (
    NAME = MyDB,
    FILENAME = <span style="color: #006080">'C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLSERVERR2_SHAY\MSSQL\DATA\MyDB.mdf'</span>,
    <span style="color: #0000ff">SIZE</span> = 10MB,
    FILEGROWTH = 1MB)
LOG <span style="color: #0000ff">ON</span> (
    NAME = MyDB_Log,
    FILENAME = <span style="color: #006080">'C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLSERVERR2_SHAY\MSSQL\DATA\MyDB_Log.ldf'</span>,
    <span style="color: #0000ff">SIZE</span> = 10MB, <span style="color: #008000">-- 10MB, 250MB, 65MB, 1025MB</span>
    FILEGROWTH = 6MB);
<span style="color: #0000ff">GO</span></pre>
</div>
<p dir="ltr">To view the size and number of the VLFs created I’ll use sys.database_files and DBCC LOGINFO.</p>
<div style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 20px 0px 10px;width: 97.5%;font-family: 'Courier New', courier, monospace;direction: ltr;font-size: 8pt;overflow: auto;cursor: text;border: silver 1px solid;padding: 4px">
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New', courier, monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #0000ff">USE</span>
    MyDB;
<span style="color: #0000ff">GO</span>

<span style="color: #0000ff">SELECT</span>
    File_Name    = name ,
    <span style="color: #0000ff">Size</span>        = <span style="color: #0000ff">CAST</span>(<span style="color: #0000ff">size</span>*8/1024 <span style="color: #0000ff">AS</span> <span style="color: #0000ff">VARCHAR</span>(10))+<span style="color: #006080">'MB'</span> , <span style="color: #008000">-- size is in pages (8KB)</span>
    Auto_Growth    = <span style="color: #0000ff">CASE</span> is_percent_growth
                    <span style="color: #0000ff">WHEN</span> 1 <span style="color: #0000ff">THEN</span> <span style="color: #0000ff">CAST</span>(growth <span style="color: #0000ff">AS</span> <span style="color: #0000ff">VARCHAR</span>(10))+<span style="color: #006080">'%'</span>
                    <span style="color: #0000ff">ELSE</span> <span style="color: #0000ff">CAST</span>(growth*8/1024 <span style="color: #0000ff">AS</span> <span style="color: #0000ff">VARCHAR</span>(10))+<span style="color: #006080">'MB'</span>
                <span style="color: #0000ff">END</span>
<span style="color: #0000ff">FROM</span> sys.database_files
<span style="color: #0000ff">WHERE</span> type_desc = <span style="color: #006080">'LOG'</span>;

<span style="color: #0000ff">DBCC</span> LOGINFO;
<span style="color: #0000ff">GO</span></pre>
</div>
<p dir="ltr"><strong>10MB:</strong></p>
<p dir="ltr">Our log file is 10MB, and as expected, we have 4 VLF files. But if we sum the size of the files we’ll get to a total of 10,477,568 Bytes while 10MB are 10,485,760 Bytes. There are 8,192 Bytes (size of a page) missing. This space is used by the file header and it does not store log records. You can see it in the StartOffset for the first VLF. This is true for all log file sizes.</p>
<p dir="ltr"><a href="http://www.madeira.co.il/wp-content/uploads/2012/01/10MB.jpg" rel="wp-prettyPhoto[g3644]"><img class="alignnone size-medium wp-image-3648" src="http://www.madeira.co.il/wp-content/uploads/2012/01/10MB-300x144.jpg" alt="" width="300" height="144" /></a></p>
<p dir="ltr">Here are the results for bigger log files:</p>
<p dir="ltr"><strong>65MB:</strong></p>
<p dir="ltr"><strong><a href="http://www.madeira.co.il/wp-content/uploads/2012/01/65MB.jpg" rel="wp-prettyPhoto[g3644]"><img class="alignnone size-medium wp-image-3649" src="http://www.madeira.co.il/wp-content/uploads/2012/01/65MB-300x192.jpg" alt="" width="300" height="192" /></a></strong></p>
<p dir="ltr"><strong>250MB:</strong></p>
<p><strong> </strong></p>
<p dir="ltr"><strong> <a href="http://www.madeira.co.il/wp-content/uploads/2012/01/250MB.jpg" rel="wp-prettyPhoto[g3644]"><img class="alignnone size-medium wp-image-3650" src="http://www.madeira.co.il/wp-content/uploads/2012/01/250MB-300x186.jpg" alt="" width="300" height="186" /></a></strong></p>
<p dir="ltr"><strong>1025MB:</strong></p>
<p dir="ltr"><strong><a href="http://www.madeira.co.il/wp-content/uploads/2012/01/1025MB.jpg" rel="wp-prettyPhoto[g3644]"><img class="alignnone size-medium wp-image-3651" src="http://www.madeira.co.il/wp-content/uploads/2012/01/1025MB-297x300.jpg" alt="" width="297" height="300" /></a></strong></p>
<p><strong> </strong></p>
<p dir="ltr">Ok, so now we know how VLFs are created, but before we continue, here’s a short overview on DBCC LOGINFO.</p>
<p dir="ltr"><strong>DBCC LOGINFO:</strong></p>
<p dir="ltr">The fields that will be relevant to better understand the VLF behavior are:</p>
<p dir="ltr"><strong>FileId</strong> – If you have one log file, this number will be the same</p>
<p dir="ltr"><strong>FileSize</strong> – This number is in Bytes</p>
<p dir="ltr"><strong>StartOffset</strong> – This number is in Bytes</p>
<p dir="ltr"><strong>FSeqNo</strong> – The file sequence number. The VLF with the highest FSeqNo is the one where current log records are being written into. FSeqNo = 0 indicates that the file hasn’t been used yet.</p>
<p dir="ltr"><strong>Status</strong> – Two possible values: 0 – VLF is recyclable, 2 – VLF may be active (Highest <strong>FSeqNo</strong> must be active)</p>
<p dir="ltr"><strong>Parity</strong> &#8211; Two possible values: 64 and 128. Every time a VLF is reused, the parity value is switched.</p>
<p dir="ltr"><strong>CreateLSN</strong> – Indicates at what LNS (Log Sequence Number) the VLF was created. CreateLSN = 0 states that the VLF was created at the time the log was created. Files with the same CreateLSN were created at the same time.</p>
<p dir="ltr">To see how the VLFs are being written on, I’ll create some activity in the DB.</p>
<p dir="ltr">The DB is set for simple recovery mode for now.</p>
<div style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 20px 0px 10px;width: 97.5%;font-family: 'Courier New', courier, monospace;direction: ltr;font-size: 8pt;overflow: auto;cursor: text;border: silver 1px solid;padding: 4px">
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New', courier, monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #0000ff">USE</span>
    MyDB;
<span style="color: #0000ff">GO</span>

<span style="color: #0000ff">ALTER</span> <span style="color: #0000ff">DATABASE</span> MyDB
<span style="color: #0000ff">SET</span> RECOVERY SIMPLE;
<span style="color: #0000ff">GO</span>

<span style="color: #0000ff">CREATE</span> <span style="color: #0000ff">TABLE</span> dbo.MyTable (<span style="color: #0000ff">Value</span> SYSNAME);

INSERT <span style="color: #0000ff">INTO</span> dbo.MyTable
<span style="color: #0000ff">SELECT</span> <span style="color: #0000ff">TOP</span> 1000 T1.name
<span style="color: #0000ff">FROM</span> sys.columns <span style="color: #0000ff">AS</span> T1
<span style="color: #0000ff">CROSS</span> <span style="color: #0000ff">JOIN</span> sys.columns <span style="color: #0000ff">AS</span> T2;
<span style="color: #0000ff">GO</span> 20</pre>
</div>
<p dir="ltr">The empty VLF files will be filled one by one until they are all full.</p>
<p dir="ltr"><a href="http://www.madeira.co.il/wp-content/uploads/2012/01/FullLog.jpg" rel="wp-prettyPhoto[g3644]"><img class="alignnone size-medium wp-image-3656" src="http://www.madeira.co.il/wp-content/uploads/2012/01/FullLog-300x147.jpg" alt="" width="300" height="147" /></a></p>
<p dir="ltr">Notice that the first 2 VLF statuses are 0. This means that these VLFs are recyclable and can be written on.</p>
<p dir="ltr">After generating more activity the first VLF has been overwritten and its FSeqNo changed from 22 to 26. Now the 3 other VLFs are recyclable and have status = 0.</p>
<p dir="ltr"><a href="http://www.madeira.co.il/wp-content/uploads/2012/01/FullLog2.jpg" rel="wp-prettyPhoto[g3644]"><img class="alignnone size-medium wp-image-3661" src="http://www.madeira.co.il/wp-content/uploads/2012/01/FullLog2-300x148.jpg" alt="" width="300" height="148" /></a></p>
<p dir="ltr"><strong>Log Truncation:</strong></p>
<p dir="ltr">Truncation is when inactive VLFs are marked as recyclable. This is a logical operation. Truncation occurs in the following events:</p>
<p dir="ltr">1) When a checkpoint occurs (only in auto truncate mode)</p>
<p dir="ltr">2) When the log is backed up (not in COPY_ONLY)</p>
<p dir="ltr">3) When the recovery mode is set to SIMPLE</p>
<p dir="ltr"><strong>Auto Truncate Mode:</strong></p>
<p dir="ltr">In Auto Truncate VLFs are being overwritten once they become inactive. The log file is in this mode when the DB is in SIMPLE recovery mode, or in FULL but no backup has been made.</p>
<p dir="ltr"><strong>Adding new VLFs (Growing the Log):</strong></p>
<p dir="ltr">In order to make the log file grow and create more VLFs we must first get out if the Auto Truncate mode. To do that, we’ll set the DB to FULL recovery mode and back it up.</p>
<div style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 20px 0px 10px;width: 97.5%;font-family: 'Courier New', courier, monospace;direction: ltr;font-size: 8pt;overflow: auto;cursor: text;border: silver 1px solid;padding: 4px">
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New', courier, monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #0000ff">ALTER</span> <span style="color: #0000ff">DATABASE</span> MyDB
<span style="color: #0000ff">SET</span> RECOVERY <span style="color: #0000ff">FULL</span>;
<span style="color: #0000ff">GO</span>

<span style="color: #0000ff">BACKUP</span> <span style="color: #0000ff">DATABASE</span> MyDB
<span style="color: #0000ff">TO</span> <span style="color: #0000ff">DISK</span> = <span style="color: #006080">'C:\Users\Shay\Documents\BackUp\MyDB_BU.bak'</span>;
<span style="color: #0000ff">GO</span></pre>
</div>
<p dir="ltr">Once we generate some more activity, all of the VLFs are full and new ones are created.</p>
<p dir="ltr"><a href="http://www.madeira.co.il/wp-content/uploads/2012/01/MoreVLFs.jpg" rel="wp-prettyPhoto[g3644]"><img class="alignnone size-medium wp-image-3666" src="http://www.madeira.co.il/wp-content/uploads/2012/01/MoreVLFs-300x173.jpg" alt="" width="300" height="173" /></a></p>
<p dir="ltr">The log file grew by 6MB and 4 new VLFs are added to it. All of the files that have already been written on (FSeqNo &gt; 0) are marked as active (Status = 2) and cannot be truncated.</p>
<p dir="ltr"><strong>Forcing Truncation:</strong></p>
<p dir="ltr">In order to be able to recycle the VLFs, we’ll buck up the <strong>Log File</strong>.</p>
<div style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 20px 0px 10px;width: 97.5%;font-family: 'Courier New', courier, monospace;direction: ltr;font-size: 8pt;overflow: auto;cursor: text;border: silver 1px solid;padding: 4px">
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New', courier, monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #0000ff">BACKUP</span> LOG MyDB
<span style="color: #0000ff">TO</span> <span style="color: #0000ff">DISK</span> = <span style="color: #006080">'C:\Users\Shay\Documents\BackUp\MyDB_LOGBU.bak'</span>;
<span style="color: #0000ff">GO</span></pre>
</div>
<p dir="ltr">After it has been bucked up, all of the VLFs are marked as inactive (Status = 0) except for the VLF that is being used at the moment. Note that the log file hasn’t shrunk, and is still 16MB.</p>
<p dir="ltr"><a href="http://www.madeira.co.il/wp-content/uploads/2012/01/Truncated1.jpg" rel="wp-prettyPhoto[g3644]"><img class="alignnone size-medium wp-image-3667" src="http://www.madeira.co.il/wp-content/uploads/2012/01/Truncated1-300x177.jpg" alt="" width="300" height="177" /></a></p>
<p dir="ltr">Now new log records can be written on the truncated VLFs.</p>
<p dir="ltr"><a href="http://www.madeira.co.il/wp-content/uploads/2012/01/OverWrite.jpg" rel="wp-prettyPhoto[g3644]"><img class="alignnone size-medium wp-image-3669" src="http://www.madeira.co.il/wp-content/uploads/2012/01/OverWrite-300x180.jpg" alt="" width="300" height="180" /></a></p>
<p dir="ltr"><strong>Deleting VLFs (Shrinking the Log):</strong></p>
<p dir="ltr">If the log file is too big, it can be shrunk by removing inactive VLFs from it. To do that we’ll make the DB go into Auto Truncate mode by set the recovery mode back to SIMPLE. If we are already in SIMPLE recovery mode, we can force a truncation by using the CHECKPOINT command.</p>
<div style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 20px 0px 10px;width: 97.5%;font-family: 'Courier New', courier, monospace;direction: ltr;font-size: 8pt;overflow: auto;cursor: text;border: silver 1px solid;padding: 4px">
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New', courier, monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #0000ff">ALTER</span> <span style="color: #0000ff">DATABASE</span> MyDB
<span style="color: #0000ff">SET</span> RECOVERY SIMPLE;
<span style="color: #0000ff">GO</span>

<span style="color: #0000ff">CHECKPOINT</span>;
<span style="color: #0000ff">GO</span></pre>
</div>
<p dir="ltr"><a href="http://www.madeira.co.il/wp-content/uploads/2012/01/Truncated2.jpg" rel="wp-prettyPhoto[g3644]"><img class="alignnone size-medium wp-image-3668" src="http://www.madeira.co.il/wp-content/uploads/2012/01/Truncated2-300x170.jpg" alt="" width="300" height="170" /></a></p>
<p dir="ltr">Now we can shrink the log file</p>
<div style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 20px 0px 10px;width: 97.5%;font-family: 'Courier New', courier, monospace;direction: ltr;font-size: 8pt;overflow: auto;cursor: text;border: silver 1px solid;padding: 4px">
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New', courier, monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #0000ff">DBCC</span> SHRINKFILE(2,5); <span style="color: #008000">-- File Id, File Size in MB</span>
GO</pre>
</div>
<p dir="ltr"><a href="http://www.madeira.co.il/wp-content/uploads/2012/01/Shrunk.jpg" rel="wp-prettyPhoto[g3644]"><img class="alignnone size-medium wp-image-3670" src="http://www.madeira.co.il/wp-content/uploads/2012/01/Shrunk-300x114.jpg" alt="" width="300" height="114" /></a></p>
<p dir="ltr">The file has shrunk to 6MB instead of 5 like we wanted. The reason is not all of the inactive VLFs are being removed during the file shrinking. In addition, the size of a single VLF can never change.</p>
<p dir="ltr"><strong>Now What?</strong></p>
<p dir="ltr">Now after we have a better understanding of how VLFs are created, truncated and deleted, and have also learned how to control these events, we as DBAs can modify our database for better performance by controlling the number of VFLs in the log file.</p>
<p dir="ltr"><strong>But what do we want to achieve?</strong></p>
<p dir="ltr">First, let’s consider our options:</p>
<p dir="ltr"><strong>Many VLFs:</strong></p>
<p dir="ltr">Having a lot of relatively small VLFs means that the log file has more flexibility during normal activity, but may cause problems during recovery and restore, and also during CHECKPOINT when in Auto Truncate mode. All of the inactive VLFs are being inspected at these events, and having a lot of then may be time consuming.</p>
<p dir="ltr">In SQL Server 2012 an error log message will appear when going over 1,000 VLFs.</p>
<p dir="ltr"><strong>Few VLFs:</strong></p>
<p dir="ltr">Having only a few big VLFs could cause problems involving truncation. A small amount of log records can prevent the VLF from being truncated. Shrinking the log file might suffer the same problems.</p>
<p dir="ltr"><strong>Bottom Line:</strong></p>
<p dir="ltr">There is no conclusive best Practice when it comes to determining the desired number of VLF files in the log. DBAs who have tested the subject report the “Sweet Spot” is around 100 VLFs. Like every other aspect of DB design, you should test it on your own system and configure it for what suits you best.</p>
<p dir="ltr">If you have tested it already, I'd like it if you could share your insights.</p>
<p><strong> </strong></p>
</div>]]></content:encoded>			<wfw:commentRss>http://www.madeira.co.il/how-are-vlfs-created-truncated-and-deleted/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>&#8235;SQL Server 2008 new data type HierarchyID&#8236;</title>		<link>http://www.madeira.co.il/the-new-data-type-hierarchyid-is-one-of-the-coolest-and-fantastic-new-features-of-sql-server-2008/</link>
		<comments>http://www.madeira.co.il/the-new-data-type-hierarchyid-is-one-of-the-coolest-and-fantastic-new-features-of-sql-server-2008/#comments</comments>
		<pubDate>Sun, 15 Jan 2012 16:47:32 +0000</pubDate>
		<dc:creator>&#8235;אסף אביב&#8236;</dc:creator>				<category><![CDATA[בלוגים]]></category>
		<category><![CDATA[כללי]]></category>
		<category><![CDATA[מקודמות]]></category>
		<category><![CDATA[features]]></category>
		<category><![CDATA[HierarchyID]]></category>
		<category><![CDATA[Madeira]]></category>
		<category><![CDATA[SQL Server 2008 R2]]></category>
		<category><![CDATA[T-SQL]]></category>
		<category><![CDATA[What's New]]></category>

		<guid isPermaLink="false">http://www.madeira.co.il/?p=3601</guid>
		<description><![CDATA[&#8235;
One of the coolest and fantastic new features of SQL Server 2008 is the new <a href="http://www.madeira.co.il/the-new-data-type-hierarchyid-is-one-of-the-coolest-and-fantastic-new-features-of-sql-server-2008/"><strong>לסיפור המלא...</strong></a>&#8236;]]></description>			<content:encoded><![CDATA[<div dir="rtl"><p><img src='http://www.madeira.co.il/wp-content/plugins/simple-post-thumbnails/timthumb.php?src=/wp-content/thumbnails/3601.jpg&amp;w=214&amp;h=129&amp;zc=1&amp;ft=jpg' alt='post thumbnail' /></p>
<p dir="rtl">One of the coolest and fantastic new features of SQL Server 2008 is the new data type HierarchyID. You’ve probably been confronted with a scenario in which you needed to data tree of some sort, and you’ve probably struggled with joins, recursive operations, and other strategies in the past. With this new type you can implement tree structures with ease, making use of the best indexing strategy.</p>
<p dir="ltr">The HierarchyID data type allows you to construct relationships among data elements within a table, specifically to represent a position in a hierarchy.</p>
<p dir="ltr">Some Facts:</p>
<p dir="ltr">-New system CLR type supporting trees.</p>
<p dir="ltr">-Extremely compact &#8211; Internally stored as varbinary &lt;= 900 bytes.</p>
<p dir="ltr">-Easy to understand &#8211; Holds a path that provides a topological sort of a tree.</p>
<p dir="ltr">-Has a set of methods that provide tree functionality: GetAncestor, GetDescendant,  GetLevel, GetRoot, IsDescendant, Parse, Read, Reparent, ToString, Write.</p>
<p dir="ltr">-Efficient querying that can utilize depth-first and breadth-first indexes.</p>
<p dir="ltr">The hierarchyid data type has the following limitations:</p>
<p dir="ltr">
<blockquote>
<p dir="ltr">-A column of type hierarchyid does not automatically represent a  tree. It is up to the application to generate and assign hierarchyid values in such a way that the desired relationship between rows is reflected in the values. Some applications might not even want to have a column of type hierarchyid represent a tree. Perhaps the values are references to location in a hierarchy defined in another table.</p>
<p dir="ltr">-It is up to the application to manage concurrency in generating and assigning hierarchyid values. There is no guarantee that hierarchyid values in a column are unique unless the application uses a unique key constraint or enforces uniqueness itself through its own logic.</p>
<p dir="ltr">-Hierarchical relationships represented by hierarchyid values are not enforced like a foreign key relationship. It is possible and sometimes appropriate to have a hierarchical relationship where A has a child B, and then A is deleted leaving B with a relationship to a nonexistent record. If this behavior is unacceptable, the application must query for descendants before deleting parents.</p>
</blockquote>
<p dir="ltr">Methods provided are as follows:</p>
<p dir="ltr">
<p dir="ltr"><strong>GetAncestor</strong>: Returns a HierarchyID that represents the n<sup>th</sup> ancestor of this HierarchyID node.</p>
<p dir="ltr"><strong>GetDescendant</strong>: Returns a child node of this HierarchyID node.</p>
<p dir="ltr"><strong>GetLevel</strong>: Returns an integer that represents the depth of this HierarchyID node in the overall hierarchy.</p>
<p dir="ltr"><strong>GetRoot</strong>: Returns the root HierarchyID node of this hierarchy tree. Static.</p>
<p dir="ltr"><strong>IsDescendant</strong>: Returns true if the passed-in child node is a descendant of this HierarchyID node.</p>
<p dir="ltr"><strong>Parse</strong>: Converts a string representation of a hierarchy to a HierarchyID value. Static.</p>
<p dir="ltr"><strong>Reparent</strong>: Moves a node of a hierarchy to a new location within the hierarchy.</p>
<p dir="ltr"><strong>ToString</strong>: Returns a string that contains the logical representation of this HierarchyID.</p>
<p dir="ltr"><strong><em>Indexing Strategies :</em></strong></p>
<p dir="ltr">There are two strategies for indexing hierarchical data:</p>
<p dir="ltr">
<p dir="ltr">-Depth-first</p>
<p dir="ltr">A depth-first index, rows in a subtree are stored near each other. For example, all employees that report through a manager are stored near their managers' record- Useful for querying subtrees.</p>
<p dir="ltr"><a href="$clip_image00142.gif"></a><a href="http://www.madeira.co.il/wp-content/uploads/2012/01/1.jpg" rel="wp-prettyPhoto[g3601]"><img class="alignnone size-full wp-image-3695" src="http://www.madeira.co.il/wp-content/uploads/2012/01/1.jpg" alt="" /></a></p>
<p dir="ltr">
<p dir="ltr">-Breadth-first</p>
<p dir="ltr">A breadth-first stores the rows each level of the hierarchy together. For example, the records of employees who directly report to the same manager are stored near each other – Useful for querying immediate children.</p>
<p dir="ltr"><a href="$clip_image00162.gif"></a><a href="http://www.madeira.co.il/wp-content/uploads/2012/01/2.jpg" rel="wp-prettyPhoto[g3601]"><img class="alignnone size-full wp-image-3696" src="http://www.madeira.co.il/wp-content/uploads/2012/01/2.jpg" alt="" /></a></p>
<p dir="ltr">
<pre style="text-align: left"><span style="font-family: Arial">Everyone found that genius but a lot broke their teeth using it in real life so let's </span></pre>
<pre style="text-align: left"><span style="font-family: Arial">Try it:</span></pre>
<pre style="text-align: left"><span style="font-family: Calibri"><span style="font-family: Arial">Let's assume we already have the following products</span> </span></pre>
<pre><a href="$image2.png"></a><a href="http://www.madeira.co.il/wp-content/uploads/2012/01/3.jpg" rel="wp-prettyPhoto[g3601]"><img class="alignnone size-full wp-image-3697" src="http://www.madeira.co.il/wp-content/uploads/2012/01/3.jpg" alt="" /></a></pre>
<pre style="text-align: left"><span style="font-family: Arial">The Idea is to represent a product tree:</span></pre>
<pre><a href="$image8.png"></a><a href="http://www.madeira.co.il/wp-content/uploads/2012/01/4.jpg" rel="wp-prettyPhoto[g3601]"><img class="alignnone size-full wp-image-3698" src="http://www.madeira.co.il/wp-content/uploads/2012/01/4.jpg" alt="" /></a></pre>
<pre style="text-align: left"><span style="font-family: Arial">First, we need to create a table to store the product hierarchy:</span></pre>
<div style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 20px 0px 10px;width: 97.5%;font-family: 'Courier New',courier,monospace;direction: ltr;font-size: 8pt;overflow: auto;cursor: text;border: 1px solid silver;padding: 4px">
<div style="text-align: left;line-height: 12pt;background-color: #f4f4f4;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px">
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   1:</span> <span style="color: #0000ff">CREATE</span> <span style="color: #0000ff">TABLE</span> dbo.ProductTree</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   2:</span> (</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   3:</span> [hierarchyid] [hierarchyid] <span style="color: #0000ff">NOT</span> <span style="color: #0000ff">NULL</span>,</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   4:</span> [Node] [nvarchar](4000) <span style="color: #0000ff">NOT</span> <span style="color: #0000ff">NULL</span>, --String representation <span style="color: #0000ff">of</span> the HierarchyID.</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   5:</span> [ProductID] [<span style="color: #0000ff">int</span>] <span style="color: #0000ff">NOT</span> <span style="color: #0000ff">NULL</span></pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   6:</span> )<span style="color: #0000ff">ON</span> [<span style="color: #0000ff">PRIMARY</span>]</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   7:</span> <span style="color: #0000ff">GO</span></pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   8:</span> <span style="color: #0000ff">CREATE</span> <span style="color: #0000ff">UNIQUE</span> <span style="color: #0000ff">CLUSTERED</span> <span style="color: #0000ff">INDEX</span> [IX_ProductTree] <span style="color: #0000ff">ON</span> dbo.ProductTree</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   9:</span> (</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  10:</span>  [hierarchyid],</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  11:</span>  [ProductID]</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  12:</span> )</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  13:</span> <span style="color: #0000ff">GO</span></pre>
<p><!--CRLF--></p>
</div>
</div>
<pre style="text-align: left"><span style="font-family: Arial">Let's start building the tree! First, the root: </span></pre>
<div style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 20px 0px 10px;width: 97.5%;font-family: 'Courier New',courier,monospace;direction: ltr;font-size: 8pt;overflow: auto;cursor: text;border: 1px solid silver;padding: 4px">
<div style="text-align: left;line-height: 12pt;background-color: #f4f4f4;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px">
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   1:</span> --Insert The Root -&gt; Product</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   2:</span> INSERT <span style="color: #0000ff">INTO</span> dbo.ProductTree</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   3:</span> (hierarchyid, Node, ProductID)</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   4:</span> <span style="color: #0000ff">VALUES</span></pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   5:</span> (hierarchyid::GetRoot(), hierarchyid::GetRoot().ToString(), 1)</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   6:</span> <span style="color: #0000ff">GO</span></pre>
<p><!--CRLF--></p>
</div>
</div>
<pre style="text-align: left"><span style="font-family: Arial">Notice the call GetRoot() to get the root node reference.</span></pre>
<pre style="text-align: left"><span style="font-family: Arial">So now we have the root node, now we need to add the first child:</span></pre>
<div style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 20px 0px 10px;width: 97.5%;font-family: 'Courier New',courier,monospace;direction: ltr;font-size: 8pt;overflow: auto;cursor: text;border: 1px solid silver;padding: 4px">
<div style="text-align: left;line-height: 12pt;background-color: #f4f4f4;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px">
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   1:</span> --Insert <span style="color: #0000ff">First</span> Child(IPhone)</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   2:</span> <span style="color: #0000ff">DECLARE</span> @ProductID <span style="color: #0000ff">INT</span> = 2 <span style="color: #008000">-- The First Child  = iPhone</span></pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   3:</span> <span style="color: #0000ff">DECLARE</span> @hierarchyid HIERARCHYID</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   4:</span> <span style="color: #0000ff">DECLARE</span> @Parenthierarchyid HIERARCHYID</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   5:</span></pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   6:</span> --<span style="color: #0000ff">Get</span> Parent hierarchyid</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   7:</span> <span style="color: #0000ff">SELECT</span> @Parenthierarchyid = hierarchyid</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   8:</span> <span style="color: #0000ff">FROM</span> dbo.ProductTree</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   9:</span> <span style="color: #0000ff">WHERE</span> ProductID = 1</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  10:</span></pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  11:</span> --<span style="color: #0000ff">Get</span> the hierarchyid</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  12:</span> <span style="color: #0000ff">SELECT</span> @hierarchyid = @Parenthierarchyid.GetDescendant(<span style="color: #0000ff">NULL</span>,<span style="color: #0000ff">NULL</span>)</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  13:</span> <span style="color: #0000ff">FROM</span> dbo.ProductTree</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  14:</span></pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  15:</span> --Insert <span style="color: #0000ff">First</span> Child(IPhone)</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  16:</span> INSERT <span style="color: #0000ff">INTO</span> dbo.ProductTree</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  17:</span> (hierarchyid, Node, ProductID)</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  18:</span> <span style="color: #0000ff">VALUES</span></pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  19:</span> (@hierarchyid, @hierarchyid.ToString(), @ProductID)</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  20:</span>  <span style="color: #0000ff">Go</span></pre>
<p><!--CRLF--></p>
</div>
</div>
<pre style="text-align: left"><span style="font-family: Arial">Notice the call GetDescendant() to get the descendant of a given node. </span></pre>
<pre style="text-align: left"><span style="font-family: Arial">It has a great significance in terms of finding the new descendant position </span></pre>
<pre style="text-align: left"><span style="font-family: Arial">Get the descendants etc.</span></pre>
<pre style="text-align: left"><span style="font-family: Arial">We'll be inserting the "Mac", in the same level, below "Product" </span></pre>
<pre style="text-align: left"><span style="font-family: Arial">And next to "iPhone".</span></pre>
<div style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 20px 0px 10px;width: 97.5%;font-family: 'Courier New',courier,monospace;direction: ltr;font-size: 8pt;overflow: auto;cursor: text;border: 1px solid silver;padding: 4px">
<div style="text-align: left;line-height: 12pt;background-color: #f4f4f4;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px">
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   1:</span> --Insert <span style="color: #0000ff">Second</span> Child(Mac)</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   2:</span> <span style="color: #0000ff">DECLARE</span> @ProductID <span style="color: #0000ff">INT</span> = 3 <span style="color: #008000">-- The Second Child = Mac</span></pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   3:</span> <span style="color: #0000ff">DECLARE</span> @FirstChildhierarchyid HIERARCHYID</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   4:</span> <span style="color: #0000ff">DECLARE</span> @hierarchyid HIERARCHYID</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   5:</span> <span style="color: #0000ff">DECLARE</span> @Parenthierarchyid HIERARCHYID</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   6:</span> --<span style="color: #0000ff">Get</span> <span style="color: #0000ff">First</span> Child hierarchyid <span style="color: #0000ff">and</span> Parent hierarchyid</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   7:</span> <span style="color: #0000ff">SELECT</span> @FirstChildhierarchyid = hierarchyid,</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   8:</span>        @Parenthierarchyid = hierarchyid.GetAncestor(hierarchyid.GetLevel())</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   9:</span> <span style="color: #0000ff">FROM</span> dbo.ProductTree</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  10:</span> <span style="color: #0000ff">WHERE</span> ProductID = 2 <span style="color: #008000">-- iPhone</span></pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  11:</span> --<span style="color: #0000ff">Get</span> the hierarchyid</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  12:</span> <span style="color: #0000ff">SELECT</span> @hierarchyid = @Parenthierarchyid.GetDescendant(@FirstChildhierarchyid,<span style="color: #0000ff">NULL</span>)</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  13:</span> <span style="color: #0000ff">FROM</span> dbo.ProductTree</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  14:</span> --Insert <span style="color: #0000ff">Second</span> Child(Mac)</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  15:</span> INSERT <span style="color: #0000ff">INTO</span> dbo.ProductTree</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  16:</span> (hierarchyid, Node, ProductID)</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  17:</span> <span style="color: #0000ff">VALUES</span></pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  18:</span> (@hierarchyid, @hierarchyid.ToString(), @ProductID)</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  19:</span></pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  20:</span> <span style="color: #0000ff">Go</span></pre>
<p><!--CRLF--></p>
</div>
</div>
<pre style="text-align: left"><span style="font-family: Arial">Notice the call GetAncestor() to get the ancestor </span></pre>
<pre style="text-align: left"><span style="font-family: Arial">Of a given child node by the level (int).</span></pre>
<p style="text-align: left" dir="ltr">Since we needed to add a new product,</p>
<p style="text-align: left" dir="ltr">At the same level of the &quot;iPhone&quot; product,</p>
<p style="text-align: left" dir="ltr">we had to get a node reference next to it, hence the @Parenthierarchyid.GetDescendant(@FirstChildhierarchyid,NULL).</p>
<p style="text-align: left" dir="ltr">Now let's add a second level child to &quot;iPhone&quot;:</p>
<p dir="ltr">
<div style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 20px 0px 10px;width: 97.5%;font-family: 'Courier New',courier,monospace;direction: ltr;font-size: 8pt;overflow: auto;cursor: text;border: 1px solid silver;padding: 4px">
<div style="text-align: left;line-height: 12pt;background-color: #f4f4f4;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px">
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   1:</span> --Insert <span style="color: #0000ff">Second</span> <span style="color: #0000ff">Level</span> Child(iPhone 4S)</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   2:</span> <span style="color: #0000ff">DECLARE</span> @ProductID <span style="color: #0000ff">INT</span> = 4 <span style="color: #008000">-- The Second Level Child = iPhone 4S</span></pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   3:</span> <span style="color: #0000ff">DECLARE</span> @hierarchyid HIERARCHYID</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   4:</span> <span style="color: #0000ff">DECLARE</span> @Parenthierarchyid HIERARCHYID</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   5:</span> --<span style="color: #0000ff">Get</span> the Parent hierarchyid</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   6:</span> <span style="color: #0000ff">SELECT</span> @Parenthierarchyid = hierarchyid</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   7:</span> <span style="color: #0000ff">FROM</span> dbo.ProductTree</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   8:</span> <span style="color: #0000ff">WHERE</span> ProductID = 2 <span style="color: #008000">-- iPhone</span></pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">   9:</span> --<span style="color: #0000ff">Get</span> the hierarchyid</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  10:</span> <span style="color: #0000ff">SELECT</span> @hierarchyid = @Parenthierarchyid.GetDescendant(<span style="color: #0000ff">NULL</span>,<span style="color: #0000ff">NULL</span>)</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  11:</span> <span style="color: #0000ff">FROM</span> dbo.ProductTree</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  12:</span> --Insert <span style="color: #0000ff">Second</span> <span style="color: #0000ff">Level</span> Child(iPhone 4S)</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  13:</span> INSERT <span style="color: #0000ff">INTO</span> dbo.ProductTree</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  14:</span> (hierarchyid, Node, ProductID)</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  15:</span> <span style="color: #0000ff">VALUES</span></pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: #f4f4f4;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  16:</span> (@hierarchyid, @hierarchyid.ToString(), @ProductID)</pre>
<p><!--CRLF--></p>
<pre style="text-align: left;line-height: 12pt;background-color: white;margin: 0em;width: 100%;font-family: 'Courier New',courier,monospace;direction: ltr;color: black;font-size: 8pt;overflow: visible;border-style: none;padding: 0px"><span style="color: #606060">  17:</span> <span style="color: #0000ff">Go</span></pre>
<p><!--CRLF--></p>
</div>
</div>
<p dir="ltr"><span style="font-family: Calibri"><strong><span style="font-family: Arial">Here is the result</span>:</strong></span></p>
<pre><a href="$clip_image0023.jpg"></a><a href="http://www.madeira.co.il/wp-content/uploads/2012/01/5.jpg" rel="wp-prettyPhoto[g3601]"><img class="alignnone size-full wp-image-3699" src="http://www.madeira.co.il/wp-content/uploads/2012/01/5.jpg" alt="" /></a></pre>
<div>
<pre style="text-align: left"><span style="font-family: Arial">?Notice the path representation and how it all fits in. Pretty neat huh</span><span style="font-family: Times New Roman;font-size: large">
Conclusion</span></pre>
</div>
<p style="text-align: left" dir="ltr">According performances, you can use the HierarchyID type without hesitation when modeling tree structures in a relational database. That new type fulfills its goal although it's not simple to implement…</p>
<pre style="text-align: left"><span style="font-family: Arial">...Hope you like this article I will write more about HierarchyID very soon</span></pre>
</div>]]></content:encoded>			<wfw:commentRss>http://www.madeira.co.il/the-new-data-type-hierarchyid-is-one-of-the-coolest-and-fantastic-new-features-of-sql-server-2008/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>

