<?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>FormatException &#187; SQL</title>
	<atom:link href="http://www.formatexception.com/category/sql/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.formatexception.com</link>
	<description>Ramblings on developing in the Windows World</description>
	<lastBuildDate>Fri, 23 Sep 2011 15:34:26 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Recursive Common Table Expressions in SQL Server for working with a hiearchy</title>
		<link>http://www.formatexception.com/2010/11/recursive-common-table-expressions-in-sql-server-for-working-with-a-hiearchy/</link>
		<comments>http://www.formatexception.com/2010/11/recursive-common-table-expressions-in-sql-server-for-working-with-a-hiearchy/#comments</comments>
		<pubDate>Thu, 04 Nov 2010 15:35:04 +0000</pubDate>
		<dc:creator>Brian</dc:creator>
				<category><![CDATA[SQL]]></category>
		<category><![CDATA[CTE]]></category>

		<guid isPermaLink="false">http://www.formatexception.com/?p=293</guid>
		<description><![CDATA[Just wanted to throw in a quick write up about common table expressions (CTE) in sql server. There are plenty of good and complete write-ups on ctes floating around teh tubes these days but I wanted to address my paticular issue, if nothing else so I don&#8217;t forget about them. Imagine you have a hiearchy [...]]]></description>
			<content:encoded><![CDATA[<p>Just wanted to throw in a quick write up about common table expressions (CTE) in sql server.</p>
<p>There are <a href="http://www.4guysfromrolla.com/webtech/071906-1.shtml">plenty of good </a>and <a href="http://msdn.microsoft.com/en-us/library/ms186243.aspx">complete write-ups </a>on ctes floating around teh tubes these days but I wanted to address my paticular issue, if nothing else so I don&#8217;t forget about them.</p>
<p>Imagine you have a hiearchy of units (like military units) though this same thing can apply to other cases like attributes or types.  Working with some made-up data you may have:</p>
<p>5th Division<br />
&nbsp;&nbsp;&nbsp;&nbsp;9th Brigade<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;17th Regiment<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;21st Regiment<br />
&nbsp;&nbsp;&nbsp;&nbsp;12 Brigade<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;54th Regiment<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;88th Regiment</p>
<p>I have a case where a user will be assigned to just one level of these units but being assigned to one level means that all child units also apply to the user.</p>
<pre name="code" class="sql">SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[_Unit_GetByUserId]
(
&nbsp;&nbsp;&nbsp;&nbsp;@UserId [uniqueidentifier]
)
AS

&nbsp;&nbsp;&nbsp;&nbsp;with c as (
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;select b.* from Unit b, UserUnit u
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;where u.UserId = @UserId
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;and b.Id = u.UnitId
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;union all
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;select b.* from Unit b
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;join c on b.ParentId = c.Id
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;where b.Id != b.ParentId
&nbsp;&nbsp;&nbsp;&nbsp;)

&nbsp;&nbsp;&nbsp;&nbsp;select * from c</pre>
<p>This allows me to get all the units that apply to the user.  In this case, if a user is assigned to the 9th Brigade then the stored proc will return: 9th Brigade, 17th Regiment, 21st Regiment</p>
<p>The key is in the union where the join to the CTE is and the ParentId is being set to the Id coming from the CTE.</p>
<p>I realize there isn&#8217;t much explanation here as to what is happening but if you follow the links above you&#8217;ll get a better explanation then I could give.</p>



Share and Enjoy:


	<a rel="nofollow"  target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.formatexception.com%2F2010%2F11%2Frecursive-common-table-expressions-in-sql-server-for-working-with-a-hiearchy%2F&amp;t=Recursive%20Common%20Table%20Expressions%20in%20SQL%20Server%20for%20working%20with%20a%20hiearchy" title="Facebook"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://news.ycombinator.com/submitlink?u=http%3A%2F%2Fwww.formatexception.com%2F2010%2F11%2Frecursive-common-table-expressions-in-sql-server-for-working-with-a-hiearchy%2F&amp;t=Recursive%20Common%20Table%20Expressions%20in%20SQL%20Server%20for%20working%20with%20a%20hiearchy" title="HackerNews"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/hackernews.png" title="HackerNews" alt="HackerNews" class="sociable-hovers" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://www.formatexception.com/2010/11/recursive-common-table-expressions-in-sql-server-for-working-with-a-hiearchy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>UpdateOrInsert (Upsert)</title>
		<link>http://www.formatexception.com/2008/10/updateorinsert-upsert/</link>
		<comments>http://www.formatexception.com/2008/10/updateorinsert-upsert/#comments</comments>
		<pubDate>Wed, 01 Oct 2008 16:20:03 +0000</pubDate>
		<dc:creator>Brian</dc:creator>
				<category><![CDATA[SQL]]></category>
		<category><![CDATA[MS SQL Server]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[Oracle]]></category>
		<category><![CDATA[PostgreSQL]]></category>

		<guid isPermaLink="false">http://www.formatexception.com/?p=78</guid>
		<description><![CDATA[Hibernate used an InsertOrUpdate (aka Upsert) method to save values (netTiers uses Save for the same thing).  This made things really simple, no need to work out if you have inserted the object, just call InsertOrUpdate and Bob&#8217;s your uncle.  Here I present the InsertOrUpdate method (well, copied from http://blogs.msdn.com/miah/archive/2008/02/17/sql-if-exists-update-else-insert.aspx but I made it universally applicable .  [...]]]></description>
			<content:encoded><![CDATA[<p>Hibernate used an InsertOrUpdate (aka Upsert) method to save values (netTiers uses Save for the same thing).  This made things really simple, no need to work out if you have inserted the object, just call InsertOrUpdate and Bob&#8217;s your uncle.  Here I present the InsertOrUpdate method (well, copied from <a class="moz-txt-link-freetext" href="http://blogs.msdn.com/miah/archive/2008/02/17/sql-if-exists-update-else-insert.aspx">http://blogs.msdn.com/miah/archive/2008/02/17/sql-if-exists-update-else-insert.aspx</a> but I made it universally applicable <span class="moz-smiley-s1"><span> <img src='http://www.formatexception.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </span></span>.  A handy little thing that lets you use do both.</p>
<p>(MS SQL)</p>
<pre name="code" class="sql">UPDATE Table1 SET (...) WHERE Column1='SomeValue'
IF @@ROWCOUNT=0
   INSERT INTO Table1 VALUES (...)</pre>
<p>It&#8217;s nice, it&#8217;s simple and does what needs to be done without a lot of work. </p>
<p>Here is the same approach can be used for postgresql, oracle and mysql.</p>
<p>(PostgreSQL)<br />
UPDATE Table1 SET (&#8230;) WHERE Column1=&#8217;SomeValue&#8217;<br />
IF NOT FOUND<br />
   INSERT INTO Table1 VALUES (&#8230;)</p>
<p>(Oracle)<br />
UPDATE Table1 SET (&#8230;) WHERE Column1=&#8217;SomeValue&#8217;<br />
IF sql%rowcount=0<br />
   INSERT INTO Table1 VALUES (&#8230;)</p>
<p>(MySQL)<br />
INSERT INTO Table1 (Column1, &#8230;) VALUES (SomeValue, &#8230;)<br />
ON DUPLICATE KEY UPDATE &#8230;</p>
<p>See also:</p>
<p><a href="http://blog.cutterscrossing.com/index.cfm/2008/2/4/SQL-Tricks-Whats-an-Upsert">http://blog.cutterscrossing.com/index.cfm/2008/2/4/SQL-Tricks-Whats-an-Upsert</a></p>
<p>UPDATE: Btw, if you&#8217;re using SQL Server 2008 you can use <a href="http://msdn.microsoft.com/en-us/library/bb510625.aspx">MERGE</a> to do this.</p>



Share and Enjoy:


	<a rel="nofollow"  target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.formatexception.com%2F2008%2F10%2Fupdateorinsert-upsert%2F&amp;t=UpdateOrInsert%20%28Upsert%29" title="Facebook"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://news.ycombinator.com/submitlink?u=http%3A%2F%2Fwww.formatexception.com%2F2008%2F10%2Fupdateorinsert-upsert%2F&amp;t=UpdateOrInsert%20%28Upsert%29" title="HackerNews"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/hackernews.png" title="HackerNews" alt="HackerNews" class="sociable-hovers" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://www.formatexception.com/2008/10/updateorinsert-upsert/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

