<?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>Eric Fickes &#187; tsql</title>
	<atom:link href="http://ericfickes.com/tag/tsql/feed/" rel="self" type="application/rss+xml" />
	<link>http://ericfickes.com</link>
	<description>Design minded Internet Programmer</description>
	<lastBuildDate>Fri, 28 Oct 2011 04:14:43 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Use INFORMATION_SCHEMA to find data about your database</title>
		<link>http://ericfickes.com/2011/02/find-out-data-about-your-database-with-system-views/</link>
		<comments>http://ericfickes.com/2011/02/find-out-data-about-your-database-with-system-views/#comments</comments>
		<pubDate>Mon, 21 Feb 2011 21:29:23 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[database]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[internets]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[automation]]></category>
		<category><![CDATA[data discovery]]></category>
		<category><![CDATA[db2]]></category>
		<category><![CDATA[information_schema]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[oracle]]></category>
		<category><![CDATA[rdmbs]]></category>
		<category><![CDATA[schemata]]></category>
		<category><![CDATA[sql server]]></category>
		<category><![CDATA[sql-92]]></category>
		<category><![CDATA[SQLSERVER]]></category>
		<category><![CDATA[system tables]]></category>
		<category><![CDATA[system views]]></category>
		<category><![CDATA[tsql]]></category>

		<guid isPermaLink="false">http://ericfickes.com/?p=2062</guid>
		<description><![CDATA[Have you ever been in this situation?  You&#8217;re the new developer for a database powered application and you have to figure out what tables contain a specific column?  Or maybe you&#8217;ve got a legacy database that needs it&#8217;s stored procedures &#8230; <a href="http://ericfickes.com/2011/02/find-out-data-about-your-database-with-system-views/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Have you ever been in this situation?  You&#8217;re the new developer for a database powered application and you have to figure out what tables contain a specific column?  Or maybe you&#8217;ve got a legacy database that needs it&#8217;s stored procedures and user defined functions cleaned up?  Or perhaps you&#8217;ve been assigned a unique database inventory task that requires you to report on the structure of your database, rather than the contents of your database.  Besides cracking open your favorite SQL editor and clicking through your database by hand, you might find the data you need from your database&#8217;s INFORMATION_SCHEMA System View.</p>
<p>All of the RDMS systems I&#8217;ve worked with have built in System Views ( or tables ) that contain data about the structure and contents of your database.  These views are there to help you with non data tasks.  For the sake of this post we&#8217;re only going mention the INFORMATION_SCHEMA, which is the system view I use most in SQL Server, and MySQL.  For your reference, here are links to INFORMATION_SCHEMA docs for four popular RDMS systems.</p>
<ol>
<li>SQL Server &#8211; <a title="SQL Server INFORMATION_SCHEMA" href="http://msdn.microsoft.com/en-us/library/ms186778.aspx" target="_blank">http://msdn.microsoft.com/en-us/library/ms186778.aspx</a></li>
<li>MySQL &#8211; <a title="MySQL INFORMATION_SCHEMA" href="http://dev.mysql.com/doc/refman/5.5/en/information-schema.html" target="_blank">http://dev.mysql.com/doc/refman/5.5/en/information-schema.html</a></li>
<li>Oracle &#8211; <a title="Oracle INFORMATION_SCHEMA" href="http://download.oracle.com/docs/cd/E17952_01/refman-5.0-en/information-schema.html" target="_blank">http://download.oracle.com/docs/cd/E17952_01/refman-5.0-en/information-schema.html</a></li>
<li>DB2 &#8211; <a title="DB2 INFORMATION_SCHEMA" href="http://www.tar.hu/sqlbible/sqlbible0100.html" target="_blank">http://www.tar.hu/sqlbible/sqlbible0100.html</a></li>
</ol>
<p>If you work with SQL Server, you&#8217;ll be happy to know you can see all of the System Views in Management Studio by default.</p>
<div id="attachment_2065" class="wp-caption aligncenter" style="width: 419px"><a href="http://ericfickes.com/wp-content/uploads/2011/02/AdventureWorks-SystemViews.png" rel="lightbox[2062]"><img class="size-full wp-image-2065" title="AdventureWorks-SystemViews" src="http://ericfickes.com/wp-content/uploads/2011/02/AdventureWorks-SystemViews.png" alt="SQL Server Management Studio shows all System Views" width="409" height="461" /></a><p class="wp-caption-text">System Views in the AdventureWorks database</p></div>
<p>If you work with MySQL, you can see the INFORMATION_SCHEMA database in MySQL Workbench, but you&#8217;ll have to enable it in Preferences first.</p>
<div id="attachment_2066" class="wp-caption aligncenter" style="width: 610px"><a href="http://ericfickes.com/wp-content/uploads/2011/02/mysql-ShowMetadataSchemata.png" rel="lightbox[2062]"><img class="size-medium wp-image-2066   " title="mysql-ShowMetadataSchemata" src="http://ericfickes.com/wp-content/uploads/2011/02/mysql-ShowMetadataSchemata-300x146.png" alt="" width="600" height="293" /></a><p class="wp-caption-text">Edit &gt; Preferences &gt; SQL Editor &gt; Check &#39;Show Metadata Schemata&#39;</p></div>
<p>Now for the MySQL users, turning on the Metadata Schemata is <em>not</em> required in order to query those system tables.  Assuming your user has appropriate permissions, you can always fire up Workbench and fire a query like this.</p>
<pre class="brush: sql; title: ; notranslate">
SELECT *
FROM INFORMATION_SCHEMA.Columns
WHERE Column_Name LIKE '%user%'
</pre>
<div id="attachment_2069" class="wp-caption aligncenter" style="width: 432px"><a href="http://ericfickes.com/wp-content/uploads/2011/02/mysql-has-info-schemas.png" rel="lightbox[2062]"><img class="size-full wp-image-2069" title="mysql-has-info-schemas" src="http://ericfickes.com/wp-content/uploads/2011/02/mysql-has-info-schemas.png" alt="" width="422" height="469" /></a><p class="wp-caption-text">MySQL has INFORMATION_SCHEMA tables too!</p></div>
<p>Now that you know about INFORMATION_SCHEMA, you should be happy to know this is part of the SQL-92 standard.  Which means whatever sql scripts you write in MySQL, will most likely work with SQL Server as well.  So go ahead and start querying your database, you&#8217;ll probably find uses for the INFORMATION_SCHEMA in your daily life really quickly.</p>
<p>I&#8217;m going to assume you&#8217;ve got the general idea here, so here are a few sql scripts that I&#8217;ve used over the years.  The first three are informational queries, and the last three are stored procedures that generate .NET or Coldfusion code based off of a table name.</p>
<p><strong>Find all tables with the column EmployeeID</strong></p>
<pre class="brush: sql; title: ; notranslate">
SELECT	*
FROM	INFORMATION_SCHEMA.COLUMNS
WHERE	COLUMN_NAME LIKE 'EmployeeID'
</pre>
<div id="attachment_2072" class="wp-caption aligncenter" style="width: 478px"><a href="http://ericfickes.com/wp-content/uploads/2011/02/1-which-tables-contain-columnName.png" rel="lightbox[2062]"><img class="size-full wp-image-2072" title="1-which-tables-contain-columnName" src="http://ericfickes.com/wp-content/uploads/2011/02/1-which-tables-contain-columnName.png" alt="" width="468" height="236" /></a><p class="wp-caption-text">Which tables have an EmployeeID column?</p></div>
<p><strong>How many tables have the word employee in the name</strong></p>
<pre class="brush: sql; title: ; notranslate">
SELECT	*
FROM	INFORMATION_SCHEMA.TABLES
WHERE	LOWER(TABLE_NAME) LIKE '%employee%'
</pre>
<div id="attachment_2073" class="wp-caption aligncenter" style="width: 483px"><a href="http://ericfickes.com/wp-content/uploads/2011/02/2-which-tables-are-named.png" rel="lightbox[2062]"><img class="size-full wp-image-2073" title="2-which-tables-are-named" src="http://ericfickes.com/wp-content/uploads/2011/02/2-which-tables-are-named.png" alt="" width="473" height="183" /></a><p class="wp-caption-text">How many %employee% tables are in the DB?</p></div>
<p><strong>How many SPROCs and UDFs does our database contain?</strong></p>
<pre class="brush: sql; title: ; notranslate">
SELECT	s.SPROCs, f.UDFs
FROM
(
	SELECT	COUNT(ROUTINE_NAME) AS 'SPROCs', NULL AS 'UDFs'
	FROM	INFORMATION_SCHEMA.ROUTINES
	WHERE	ROUTINE_TYPE = 'PROCEDURE'
) AS s,
(
	SELECT	NULL AS 'SPROCs', COUNT(ROUTINE_NAME) AS 'UDFs'
	FROM	INFORMATION_SCHEMA.ROUTINES
	WHERE	ROUTINE_TYPE = 'FUNCTION'
) AS f
</pre>
<div id="attachment_2076" class="wp-caption aligncenter" style="width: 159px"><a href="http://ericfickes.com/wp-content/uploads/2011/02/3-how-many-sprocs-udfs.png" rel="lightbox[2062]"><img class="size-full wp-image-2076" title="3-how-many-sprocs-udfs" src="http://ericfickes.com/wp-content/uploads/2011/02/3-how-many-sprocs-udfs.png" alt="" width="149" height="65" /></a><p class="wp-caption-text">How many stored procedures and user defined functions are in the DB?</p></div>
<p>The stored procedures listed below all accept an incoming table name, then reads data from INFORMATION_SCHEMA to generate code for the specified database table.  Instead of listing the raw SQL, I&#8217;m just showing a sample result and allowing you to download the raw SQL sprocs.</p>
<p><strong>Generate C# ADO.NET to VO Stored Procedure</strong></p>
<div id="attachment_2077" class="wp-caption aligncenter" style="width: 583px"><a href="http://ericfickes.com/wp-content/uploads/2011/02/4-create-sproc-generateGetTableCode.png" rel="lightbox[2062]"><img class="size-full wp-image-2077" title="4-create-sproc-generateGetTableCode" src="http://ericfickes.com/wp-content/uploads/2011/02/4-create-sproc-generateGetTableCode.png" alt="" width="573" height="458" /></a><p class="wp-caption-text">Build custom C# ADO.NET to custom VO fillerup code</p></div>
<p><a title="Download 'Generate C# ADO.NET to VO' Stored Procedure" href="http://ericfickes.com/code/INFO_SCHEMA/DotNet-generateGetTableCode.sql" target="_blank">download stored procedure</a></p>
<p><a title="Download 'Generate C# ADO.NET to VO' Stored Procedure" href="http://ericfickes.com/code/INFO_SCHEMA/DotNet-generateGetTableCode.sql" target="_blank"></a><br />
<strong>Generate .NET VO class Stored Procedure</strong></p>
<p><a href="http://ericfickes.com/wp-content/uploads/2011/02/5-create-sproc-generateTableVoClass.png" rel="lightbox[2062]"><img class="aligncenter size-full wp-image-2078" title="5-create-sproc-generateTableVoClass" src="http://ericfickes.com/wp-content/uploads/2011/02/5-create-sproc-generateTableVoClass.png" alt="Generate C# VO class for DB table name" width="315" height="454" /></a></p>
<p><a title="Download 'Generate .NET VO class' stored procedure" href="http://ericfickes.com/code/INFO_SCHEMA/DotNet-generateTableVoClass.sql" target="_blank">download stored procedure</a></p>
<p><strong>Generate Coldfusion CFFunction with CFQUERY Stored Procedure</strong></p>
<div id="attachment_2079" class="wp-caption aligncenter" style="width: 502px"><a href="http://ericfickes.com/wp-content/uploads/2011/02/6-create-sproc-MakeSelectFromDbTable.png" rel="lightbox[2062]"><img class="size-full wp-image-2079" title="6-create-sproc-MakeSelectFromDbTable" src="http://ericfickes.com/wp-content/uploads/2011/02/6-create-sproc-MakeSelectFromDbTable.png" alt="" width="492" height="276" /></a><p class="wp-caption-text">Generate Coldfusion CFFunction with CFQUERY for specified table name</p></div>
<p><a title="Download 'Generate Coldfusion CFFunction with CFQUERY' stored procedure" href="http://ericfickes.com/code/INFO_SCHEMA/Coldfusion-MakeSelectFromDbTable.sql" target="_blank">download stored procedure</a></p>
<p>I use these System Views almost daily, and there are a lot of scenarios where my job would take a lot longer to do if I didn&#8217;t know about this information.  The INFORMATION_SCHEMA also feeds my passion to build code that makes code, just love it.  Hopefully this nickel tour was enough information to help somebody out.</p>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2011/02/find-out-data-about-your-database-with-system-views/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
<enclosure url="http://ericfickes.com/code/INFO_SCHEMA/DotNet-generateGetTableCode.sql" length="17232" type="audio/mpeg" />
		</item>
		<item>
		<title>Today I took 30 minutes to save hours</title>
		<link>http://ericfickes.com/2011/01/today-i-took-30-minutes-to-save-hours/</link>
		<comments>http://ericfickes.com/2011/01/today-i-took-30-minutes-to-save-hours/#comments</comments>
		<pubDate>Tue, 04 Jan 2011 04:21:41 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[database]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[tips and tricks]]></category>
		<category><![CDATA[automation]]></category>
		<category><![CDATA[backup]]></category>
		<category><![CDATA[bat]]></category>
		<category><![CDATA[batch]]></category>
		<category><![CDATA[batch file]]></category>
		<category><![CDATA[cli]]></category>
		<category><![CDATA[cmd]]></category>
		<category><![CDATA[command line]]></category>
		<category><![CDATA[cursor]]></category>
		<category><![CDATA[DECLARE]]></category>
		<category><![CDATA[del]]></category>
		<category><![CDATA[exec]]></category>
		<category><![CDATA[fetch]]></category>
		<category><![CDATA[fetch_status]]></category>
		<category><![CDATA[information_schema]]></category>
		<category><![CDATA[kill]]></category>
		<category><![CDATA[restore]]></category>
		<category><![CDATA[sproc]]></category>
		<category><![CDATA[sqlcmd]]></category>
		<category><![CDATA[sys]]></category>
		<category><![CDATA[tsql]]></category>
		<category><![CDATA[workflow]]></category>

		<guid isPermaLink="false">http://ericfickes.com/?p=1861</guid>
		<description><![CDATA[UPDATE &#8211; 1/6/2011 : Since writing this post I have bundled this entire reset process into a single windows batch file. In addition to restoring my database, I also have to remove temp files from my server, so it was &#8230; <a href="http://ericfickes.com/2011/01/today-i-took-30-minutes-to-save-hours/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><strong> </strong><strong>UPDATE &#8211; </strong><strong>1/6/2011 : </strong>Since writing this post I have bundled this entire reset process into a single <a title="How to use windows batch files" href="http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/batch.mspx?mfr=true" target="_blank">windows batch file</a>. In addition to restoring my database, I also have to remove temp files from my server, so it was time to go command line with all of this.</p>
<p>Here the contents of my batch file.</p>
<pre class="brush: plain; title: ; notranslate">
### DELETE TEMP FILES
del /q /f /s Z:\_FavoriteClient\_GIT_\webapp\invoices\* /f /s

### RESTORE DATABASE
sqlcmd -S &quot;localhost&quot; -i Z:\_FavoriteClient\_GIT_\sql\restoreBackup.sql
</pre>
<p>To use this in a .bat file, copy and paste the text into Notepad, then save as &#8220;restore.bat&#8221;.  Remember, you will need to wrap your filename.bat with quotes, otherwise Notepad will save the file as filename.bat.txt.</p>
<p>* The contents of restoreBackup.sql is listed below.</p>
<hr style="color: efefef;" size="1" noshade="noshade" />One of my favorite pastimes as a programmer is writing code that writes code, aka workflow automation.  It&#8217;s not something I do on every project, but I&#8217;ve been doing a lot of SQL Server development recently, and I&#8217;ve been having a lot of fun using the <a title="SQL 2008 RS Information Schema Views (Transact-SQL)" href="http://msdn.microsoft.com/en-us/library/ms186778.aspx" target="_blank">INFORMATION_SCHEMA views</a> to <a title="Use TSQL to generate Actionscript VO classes" href="http://ericfickes.posterous.com/tsql-sproc-generatetablevoclass" target="_blank">build VO classes</a>, forms representing tables, or just finding what tables have a specific column.  Today I took a 30 minute trip to the <a title="SQL 2008 SYS tables" href="http://msdn.microsoft.com/en-us/library/ms187406.aspx" target="_blank">SYS side</a> and wrote a tsql script that will save me hours.</p>
<p>The web application I&#8217;m working on is a payment processor made up of five steps.  In order to test I have to setup multiple sales for multiple clients, then log in as three different admin users to push the transactions through the system.  This gets my test transactions to the proper testable state.  The process of setting up testable transactions takes over 30 clicks, and once I hit step 3 of the wizard, my test transactions are completed in a way that I have to re-setup the test data ( 20 GOTO 10 ).</p>
<p>I thought about a handful of options, and ended up going with this solution.</p>
<ol>
<li>Setup all test transactions in web application by hand ( get the data ready )</li>
<li>Take a full database backup ( freeze the data )</li>
<li>Use TSQL script to drop all connections to my app&#8217;s db, then restore the database to the &#8220;testable&#8221; state from step 1 ( reset the DB )</li>
</ol>
<p>Here is my TSQL script</p>
<pre class="brush: sql; title: ; notranslate">
DECLARE @sessID int,
		@dbName varchar(50),
		@userName varchar(50),
		@backupFile varchar(200)

SET @dbName		= 'DA413'	-- your database name
SET @userName	= 'DA413'	-- sql user account to look for
SET @backupFile = 'D:\DB\Backup\DA413.bak' -- path to SQL backup file

-- use a cursor to store all session_ids
DECLARE session_cursor CURSOR
FOR
	SELECT	session_id
	FROM	sys.dm_exec_sessions
	WHERE	original_login_name = @userName

	-- open cursor and grab first row
	OPEN session_cursor
	FETCH NEXT FROM session_cursor INTO @sessID

	-- loop through session_ids
	WHILE @@FETCH_STATUS = 0
	BEGIN

		-- kill it
		-- using EXEC because the sproc kill does not like @variables
		EXEC('kill ' + @sessID)

		-- get the next session_id
		FETCH NEXT FROM session_cursor INTO @sessID
	END

-- cursor cleanup
CLOSE session_cursor
DEALLOCATE session_cursor

-- restore backup
USE master
	RESTORE DATABASE DA413
	FROM DISK = @backupFile
GO
</pre>
<p>A few notes about this script :</p>
<ul>
<li>I only need to disconnect my web application&#8217;s database user, not any user</li>
<li>I&#8217;m using the latest full backup, and not a specific database snapshot</li>
<li>The SPROC <a title="TSQL KILL sproc" href="http://technet.microsoft.com/en-us/library/ms173730.aspx" target="_blank">kill</a> doesn&#8217;t like @variables as input, so use <a title="TSQL EXEC" href="http://msdn.microsoft.com/en-us/library/ms188332.aspx" target="_blank">EXEC</a></li>
<li>Your web server doesn&#8217;t know the user was disconnected, so you&#8217;ll have to log back into your application.</li>
<li>If you use this technique, be sure to RERUN your backup if you add anything to the database ( EX : new table column, stored procedure, etc )</li>
<li>If you&#8217;re not the only person connected to this database, make sure you don&#8217;t disconnect anybody else using the same database name</li>
</ul>
<p>This solution is perfect for me because I have full control over my code, database, and server.  It&#8217;s also great because I can test my application, run a single sql script, and 10 seconds later I can test my application again.  While this solution is perfect for me, it&#8217;s probably best used as reference for others.  However, this technique of rolling back the database could be applied to <em>any</em> software application using SQL Server for it&#8217;s datasource.</p>
<p>Hope this helps somebody.</p>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2011/01/today-i-took-30-minutes-to-save-hours/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Selecting random ids using TOP and a CTE</title>
		<link>http://ericfickes.com/2010/09/selecting-random-ids-using-top-and-a-cte/</link>
		<comments>http://ericfickes.com/2010/09/selecting-random-ids-using-top-and-a-cte/#comments</comments>
		<pubDate>Thu, 30 Sep 2010 05:43:49 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[database]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[tips and tricks]]></category>
		<category><![CDATA[tsql]]></category>
		<category><![CDATA[common table expression]]></category>
		<category><![CDATA[cte]]></category>
		<category><![CDATA[mssqlserver]]></category>
		<category><![CDATA[sql server]]></category>
		<category><![CDATA[SQLSERVER]]></category>
		<category><![CDATA[top]]></category>

		<guid isPermaLink="false">http://ericfickes.com/?p=1675</guid>
		<description><![CDATA[While testing visualizations in a Flex application, I needed to do some underlying data cleanup in SQL Server.  One of my tasks was to manually update an entity table and set the status column to one of three possibilities.  Status &#8230; <a href="http://ericfickes.com/2010/09/selecting-random-ids-using-top-and-a-cte/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>While testing visualizations in a Flex application, I needed to do some underlying data cleanup in SQL Server.  One of my tasks was to manually update an entity table and set the status column to one of three possibilities.  Status group A and B both needed to be roughly 20% of my tables total record count, and status group C would be the remaining rows that weren&#8217;t touched by status A or status B.  Oh and there&#8217;s one more thing, the ids in each status group can not be in sequential order, they have to be random.</p>
<p>At first I thought no sweat.  My dataset is still small ( only 2000 rows ), so if we want uber control I could do the math and generate my id lists by hand.  Yes, hand crafting is possible and under a deadline that kind of logic almost makes sense.  However, I already know the table I&#8217;m working with will grow in the future, and I&#8217;ll probably have to do this data update again, so why not do this right?  While playing around with different select statements I had a &#8220;EUREKA!&#8221; moment.  <a title="TSQL's TOP operator on MSDN" href="http://msdn.microsoft.com/en-us/library/ms189463.aspx" target="_blank">SQL Server&#8217;s TOP operator</a> supports PERCENT, not just number.  I couldn&#8217;t believe it.  I use TOP at least once a week and I always forget about TOP PERCENT.  Since I already know how to select random rows via <a title="SQL Server's Common Table Expressions are super helpful" href="http://msdn.microsoft.com/en-us/library/ms190766.aspx" target="_blank">CTE</a>, it  was time to put it all together.</p>
<p>Before giving you the final SQL, here are the important parts to be familiar with.  Also, for the sake of example I&#8217;m using the <a title="Download the AdventureWorks database from Codeplex" href="http://msftdbprodsamples.codeplex.com/releases/view/37109" target="_blank">AdventureWorks database</a> so you can play along at home.</p>
<h2><a title="MSSQL's TOP operator on MSDN" href="http://msdn.microsoft.com/en-us/library/ms189463.aspx" target="_blank">TOP PERCENT</a></h2>
<p>If you just need 50% of the rows in a table, but you&#8217;re not concerned about the sequence returned, you can fire this query.  This will give you a sequential listing of ProductIDs</p>
<pre class="brush: sql; title: ; notranslate">
SELECT TOP 50 PERCENT ProductID
FROM Production.Product
ORDER BY ProductID
</pre>
<p>Which will look something like this.</p>
<p><a href="http://ericfickes.com/wp-content/uploads/2010/09/SELECT-TOP-20-PERCENT.png" rel="lightbox[1675]"><img class="aligncenter size-full wp-image-1682" title="SELECT TOP 20 PERCENT" src="http://ericfickes.com/wp-content/uploads/2010/09/SELECT-TOP-20-PERCENT.png" alt="SQL's TOP operator returns rows sequentially" width="274" height="255" /></a></p>
<h2><a title="A Common Table Expression can be thought of as a temporary result set that is defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement. A CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query..." href="http://msdn.microsoft.com/en-us/library/ms190766.aspx" target="_blank">COMMON TABLE EXPRESSION</a></h2>
<p>Now let&#8217;s say you want to randomly pull all rows from a table.  This can be achieved using this CTE.</p>
<pre class="brush: sql; title: ; notranslate">
WITH data( ProductID ) AS (
	SELECT	ProductID
	FROM	Production.Product
)
SELECT	ProductID
FROM	data
ORDER BY NEWID()
</pre>
<p>Which will look like this</p>
<p><a href="http://ericfickes.com/wp-content/uploads/2010/09/SELECT-RANDOM-CTE.png" rel="lightbox[1675]"><img class="aligncenter size-full wp-image-1689" title="SELECT RANDOM DATA using CTE" src="http://ericfickes.com/wp-content/uploads/2010/09/SELECT-RANDOM-CTE.png" alt="Common Table Expressions in SQLSERVER are super helpful" width="271" height="381" /></a></p>
<p>If you&#8217;re looking to <a title="Select random value from preset list - tSQL, CTE" href="http://ericfickes.posterous.com/tsql-select-a-random-value-using-cte" target="_blank">randomly select values from a pre-determined list, see my CTE sample here</a>.</p>
<p>So now that you&#8217;ve seen TOP PERCENT and CTE in action, it&#8217;s time to put these together and solve my initial task of creating randomly selected groups of ids, of a percent size.</p>
<p>RANDOMLY SELECT TOP PERCENT</p>
<p>Putting it all together, here is the query I used to create my first status group.</p>
<pre class="brush: sql; title: ; notranslate">
WITH data( ProductID ) AS (
	SELECT	ProductID
	FROM	Production.Product
)
SELECT TOP 20 PERCENT ProductID
FROM	data
ORDER BY NEWID()
</pre>
<p>Which gives me a dataset that is 20% of all rows in Production.Product, and the ids are in random order.</p>
<p>And there you have it.  Randomly selecting a percent sized data set from a table in SQL Server.  The SQL here is really pretty simple, but for some reason I always forget TOP PERCENT.  I&#8217;m hoping this post will help me remember TOP PERCENT, and maybe even help somebody else with some TSQL.</p>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2010/09/selecting-random-ids-using-top-and-a-cte/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What if you want to PIVOT against a text column?</title>
		<link>http://ericfickes.com/2010/04/what-if-you-want-to-pivot-against-a-text-column/</link>
		<comments>http://ericfickes.com/2010/04/what-if-you-want-to-pivot-against-a-text-column/#comments</comments>
		<pubDate>Sat, 01 May 2010 05:04:27 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[database]]></category>
		<category><![CDATA[microsoft]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[tips and tricks]]></category>
		<category><![CDATA[tsql]]></category>
		<category><![CDATA[coalesce]]></category>
		<category><![CDATA[dynamic sql]]></category>
		<category><![CDATA[exec]]></category>
		<category><![CDATA[pivot]]></category>
		<category><![CDATA[quotename]]></category>
		<category><![CDATA[SQLSERVER]]></category>
		<category><![CDATA[table variable]]></category>

		<guid isPermaLink="false">http://ericfickes.com/?p=1435</guid>
		<description><![CDATA[If you&#8217;ve ever worked with or researched SQL Server&#8217;s PIVOT function, you probably noticed most of the samples pivot against an id column.  Typically an int column like EmployeeID, or StoreID.  That&#8217;s fine and dandy, but what happens when you &#8230; <a href="http://ericfickes.com/2010/04/what-if-you-want-to-pivot-against-a-text-column/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;ve ever worked with or researched SQL Server&#8217;s <a title="Using PIVOT and UNPIVOT functions" href="http://msdn.microsoft.com/en-us/library/ms177410.aspx" target="_blank">PIVOT function</a>, you probably noticed most of the samples pivot against an id column.  Typically an int column like EmployeeID, or StoreID.  That&#8217;s fine and dandy, but what happens when you want to PIVOT against a varchar column?  If you&#8217;ve been in this need you know this is a bit of a task.</p>
<p>I had this need on an app recently and built a little dynamic sql action that does just this.  The example below however, uses the the <a title="DatabaseLog table in the AdventureWorks DB" href="http://msdn.microsoft.com/en-us/library/ms124872.aspx" target="_blank">DatabaseLog</a> table in the <a title="Download AdventureWorks sample databases for free" href="http://msdn.microsoft.com/en-us/library/ms124501(v=SQL.100).aspx" target="_blank">AdventureWorks sample database</a> to return a count of Events logged for each Schema.  Before jumping into the PIVOT, here&#8217;s a simple query that gives you the same information, all Schemas, Events, and Event counts.</p>
<pre class="brush: sql; title: ; notranslate">
SELECT      [Schema], [Event], COUNT( [Event] ) AS 'event_count'
FROM        DatabaseLog
GROUP BY    [Schema], [Event]
ORDER BY    [Schema]
</pre>
<p>Running this query should give you a long result looking something like this.</p>
<p><a href="http://ericfickes.com/wp-content/uploads/2010/04/regular_count_query.png" rel="lightbox[1435]"><img class="aligncenter size-full wp-image-1442" title="Regular COUNT query" src="http://ericfickes.com/wp-content/uploads/2010/04/regular_count_query.png" alt="Data is there, format isn't nice like PIVOT" width="409" height="394" /></a></p>
<p>While this query returns the same information to you, I don&#8217;t like this format as much as using PIVOT.  This query result is long and requires a bit of manipulation to get into a readable format.</p>
<p>Now let&#8217;s have a look at retrieving the same information using the PIVOT function.</p>
<pre class="brush: sql; title: ; notranslate">
/*
Example of a dynamic PIVOT against a varchar column from the Adventureworks database

References :
PIVOT &amp; UNPIVOT function

http://msdn.microsoft.com/en-us/library/ms177410.aspx

AdventureWorks sample Databases

http://msdn.microsoft.com/en-us/library/ms124501(v=SQL.100).aspx

AdventreWorks.DatabaseLog

http://msdn.microsoft.com/en-us/library/ms124872.aspx

*/

USE AdventureWorks

-- populate temp Event table
SELECT DISTINCT [Event] as 'Event'
INTO	#events
FROM	DatabaseLog

-- this var will hold a comma delimited list of [Event]
DECLARE	@eventList nvarchar(max)

-- create a flattened [Event], list for the PIVOT statement
SELECT	@eventList = COALESCE( @eventList + ', ', '') + CAST( QUOTENAME( [Event] ) AS VARCHAR(1000) )
FROM	#events
ORDER BY [Event]

-- drop table var since our data now lives in @eventList
DROP TABLE #events

-- this var will hold the dynamic PIVOT sql
DECLARE @pvt_sql nvarchar(max)

-- NOTE : we're using dynamic sql here because PIVOT
-- does not support sub SELECT in the 'FOR Event IN ( )'
-- part of the query.
-- If we don't use dynamic SQL here, the PIVOT function
-- requires you to hard code each 'Event'
-- Using SELECT * here so the [Event] columns are auto included
SET @pvt_sql = 'SELECT	*
                FROM
                (
                    SELECT	[Event], [Schema]
                    FROM	DatabaseLog
                ) AS data
                PIVOT
                (
                    COUNT( Event )
                    FOR Event IN
                    ( ' + @eventList + ' )
                ) AS pvt'

-- run the query
EXEC sp_executesql @pvt_sql
</pre>
<p>Assuming you have the AdventureWorks database installed on your server, running this sql should give you a result looking something like this.</p>
<div id="attachment_1439" class="wp-caption aligncenter" style="width: 597px"><a href="http://ericfickes.com/wp-content/uploads/2010/04/dynamic_pivot_dblog.png" rel="lightbox[1435]"><img class="size-full wp-image-1439" title="Schema Event counts" src="http://ericfickes.com/wp-content/uploads/2010/04/dynamic_pivot_dblog.png" alt="Dynamic PIVOT on text column Event" width="587" height="143" /></a><p class="wp-caption-text">Show all Schemas and count of each Event type</p></div>
<p>This query result was truncated to fit in this post, but just know the query above creates a column for every Event in the Databaselog table.</p>
<p>A quick explanation of what&#8217;s happening in this sql</p>
<ol>
<li>First you fill a table variable ( #events ) with all Events from DatabaseLog</li>
<li>Next create a comma delimited list of the Events inside of the table variable</li>
<li>Drop the table variable now that we&#8217;ve got our delimited list of Events</li>
<li>Build the PIVOT statement as a string so you can inject the Events list</li>
<li>Fire the dynamic SQL via EXEC</li>
</ol>
<p>Dynamic SQL is something that comes in handy from time to time, but I do my best to only use it if I absolutely have to.  In this case we&#8217;re using it because the PIVOT function does not allow sub SELECT statements.  This is also why we create a specially formatted delimited list of Events prior to building the dynamic sql.</p>
<p>So there you have it, one example of using PIVOT against a varchar column instead of an integer column.  Also, this is a pretty good example of a dynamic PIVOT since it&#8217;s pretty simple.  I hope this makes sense, and if you have any suggestions of better techniques, I&#8217;d love to hear it.</p>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2010/04/what-if-you-want-to-pivot-against-a-text-column/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Incorrect syntax near the keyword &#8216;table&#8217; in TSQL</title>
		<link>http://ericfickes.com/2010/04/incorrect-syntax-near-the-keyword-table-in-tsql/</link>
		<comments>http://ericfickes.com/2010/04/incorrect-syntax-near-the-keyword-table-in-tsql/#comments</comments>
		<pubDate>Wed, 07 Apr 2010 22:18:21 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[database]]></category>
		<category><![CDATA[microsoft]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[tsql]]></category>
		<category><![CDATA[#table]]></category>
		<category><![CDATA[DECLARE]]></category>
		<category><![CDATA[SQLSERVER]]></category>
		<category><![CDATA[SQLSERVER 2005]]></category>
		<category><![CDATA[table variable]]></category>

		<guid isPermaLink="false">http://ericfickes.com/2010/04/incorrect-syntax-near-the-keyword-table-in-tsql/</guid>
		<description><![CDATA[Ran into something little that I know I&#8217;m going to forget if I don&#8217;t write down. It appears that when using a TABLE variable in tsql ( SQL Server 2005 ), you must DECLARE that variable on it&#8217;s own line, &#8230; <a href="http://ericfickes.com/2010/04/incorrect-syntax-near-the-keyword-table-in-tsql/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Ran into something little that I know I&#8217;m going to forget if I don&#8217;t write down.  It appears that when using a TABLE variable in tsql ( SQL Server 2005 ), you must DECLARE that variable on it&#8217;s own line, as opposed to inline with your other @variables.</p>
<p>Typically in my sprocs or sql scripts I do my best to have a main DECLARE block and seperate my @variables with a comma like this.</p>
<div id="attachment_1412" class="wp-caption aligncenter" style="width: 378px"><a href="http://ericfickes.com/wp-content/uploads/2010/04/declare-bad.png" rel="lightbox[1414]"><img class="size-full wp-image-1412" title="Incorrect syntax near the keyword 'table'" src="http://ericfickes.com/wp-content/uploads/2010/04/declare-bad.png" alt="Typically I DECLARE=" width="368" height="125" /></a><p class="wp-caption-text">If you&#39;re using a TABLE variable, put it on it&#39;s own DECLARE line</p></div>
<p>After some mucking around, it turns out moving the TABLE @variable to it&#8217;s own DECLARE line fixes this issue.</p>
<div id="attachment_1413" class="wp-caption aligncenter" style="width: 304px"><a href="http://ericfickes.com/wp-content/uploads/2010/04/declare-good.png" rel="lightbox[1414]"><img class="size-full wp-image-1413" title="DECLARE TABLE @variables on their own line" src="http://ericfickes.com/wp-content/uploads/2010/04/declare-good.png" alt="DECLARE TABLE @variables on their own line" width="294" height="106" /></a><p class="wp-caption-text">DECLARE TABLE @variables on their own line</p></div>
<p>I haven&#8217;t found this info in SQL BOL, so I hope this helps somebody else.</p>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2010/04/incorrect-syntax-near-the-keyword-table-in-tsql/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>What happens in EXEC, stays in EXEC. Lifespan of a MSSQL table variable</title>
		<link>http://ericfickes.com/2010/02/using-mssql-table-variables-with-exec-statements/</link>
		<comments>http://ericfickes.com/2010/02/using-mssql-table-variables-with-exec-statements/#comments</comments>
		<pubDate>Mon, 15 Feb 2010 19:44:49 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[database]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[tsql]]></category>
		<category><![CDATA[exec]]></category>
		<category><![CDATA[mssql]]></category>
		<category><![CDATA[mssql2000]]></category>
		<category><![CDATA[mssql2005]]></category>
		<category><![CDATA[scope]]></category>
		<category><![CDATA[SELECT INTO]]></category>
		<category><![CDATA[table variable]]></category>
		<category><![CDATA[temp table]]></category>

		<guid isPermaLink="false">http://ericfickes.com/?p=1080</guid>
		<description><![CDATA[One of my all time favorite features of MSSQL 2005+ is being able to create table variables on the fly from SELECT statements. This isn&#8217;t a lesson in what table variables are, but here is an easy sample in case &#8230; <a href="http://ericfickes.com/2010/02/using-mssql-table-variables-with-exec-statements/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p style="text-align: left;">One of my all time favorite features of MSSQL 2005+ is being able to create table variables on the fly from SELECT statements.  This isn&#8217;t a lesson in what table variables are, but here is an easy sample in case this is a new concept.</p>
<p style="text-align: left;">Running this query</p>
<pre class="brush: sql; title: ; notranslate">SELECT * INTO #myTableVar FROM YourTable</pre>
<p>Gives you a new table variable named myTableVar.  Table variables are scoped to the active connection, so running this will work.</p>
<pre class="brush: sql; title: ; notranslate">
// make table var
SELECT * INTO #myTableVar FROM YourTable
// show me the data
SELECT * FROM #myTableVar
// you can drop it if you wish
DROP TABLE #myTableVar
</pre>
<p>However, let&#8217;s say you have an aspx page or a sproc that runs this query.</p>
<pre class="brush: sql; title: ; notranslate">SELECT * INTO #myTableVar FROM YourTable</pre>
<p>You can not access myTableVar in a separate connection to the database because as soon as the first query&#8217;s connection closes, myTableVar gets dropped.     Here are a few other scenarios that also demonstrate the scoping of a table variable.</p>
<pre class="brush: sql; title: ; notranslate">
-- FAILS
EXEC ('SELECT * INTO #tmp FROM MyTable;');
-- #tmp does not exist
SELECT * FROM #tmp
</pre>
<div id="attachment_1084" class="wp-caption aligncenter" style="width: 404px"><a href="http://ericfickes.com/wp-content/uploads/2010/02/exec1-no-tmp-table.png" rel="lightbox[1080]"><img class="size-full wp-image-1084      " title="Table variable lives inside of EXEC" src="http://ericfickes.com/wp-content/uploads/2010/02/exec1-no-tmp-table.png" alt="#tmp only exists inside of EXEC" width="394" height="179" /></a><p class="wp-caption-text">Table variable #tmp lives inside of EXEC</p></div>
<p>Here we see that the table variable #tmp only lives for the life of the statement inside of EXEC.  The second SELECT * calls is outside of the EXEC statement.</p>
<pre class="brush: sql; title: ; notranslate">
-- #tmp2 works inside of EXEC statement
EXEC ('SELECT * INTO #tmp2 FROM MyTable; SELECT * FROM #tmp2');
</pre>
<div id="attachment_1086" class="wp-caption aligncenter" style="width: 570px"><a href="http://ericfickes.com/wp-content/uploads/2010/02/exec2-tmp-inside-exec.png" rel="lightbox[1080]"><img class="size-full wp-image-1086   " title="tmp2 lives inside of EXEC" src="http://ericfickes.com/wp-content/uploads/2010/02/exec2-tmp-inside-exec.png" alt="table variables in EXEC live in EXEC" width="560" height="111" /></a><p class="wp-caption-text">What happens in EXEC, stays in EXEC</p></div>
<p>Here #tmp2 works because it&#8217;s being used inside of the EXEC statement.  This is worth knowing if you work with dynamic sql statements and exec.</p>
<pre class="brush: sql; title: ; notranslate">
-- works!
SELECT * INTO #tmp FROM MyTable;
-- #tmp exists
SELECT * FROM #tmp
</pre>
<div id="attachment_1087" class="wp-caption aligncenter" style="width: 318px"><a href="http://ericfickes.com/wp-content/uploads/2010/02/exec3-normal-tmp-exists.png" rel="lightbox[1080]"><img class="size-full wp-image-1087" title="typical sample of using mssql table variable" src="http://ericfickes.com/wp-content/uploads/2010/02/exec3-normal-tmp-exists.png" alt="typical sample of using mssql table variable" width="308" height="153" /></a><p class="wp-caption-text">typical sample of using mssql table variable</p></div>
<p>This is a typical example that you may use inside a sproc, trigger, script, etc.  Both sql calls live in the same space, so #tmp exists.</p>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2010/02/using-mssql-table-variables-with-exec-statements/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Select random value from a range of values</title>
		<link>http://ericfickes.com/2010/01/select-random-value-from-a-range-of-values/</link>
		<comments>http://ericfickes.com/2010/01/select-random-value-from-a-range-of-values/#comments</comments>
		<pubDate>Sun, 03 Jan 2010 01:08:52 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[database]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[microsoft]]></category>
		<category><![CDATA[tips and tricks]]></category>
		<category><![CDATA[tsql]]></category>
		<category><![CDATA[#table]]></category>
		<category><![CDATA[cte]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[mssql]]></category>
		<category><![CDATA[mssql2000]]></category>
		<category><![CDATA[mssql2005]]></category>
		<category><![CDATA[random]]></category>
		<category><![CDATA[table variable]]></category>

		<guid isPermaLink="false">http://ericfickes.com/?p=1020</guid>
		<description><![CDATA[Earlier I blogged about creating random numbers using tsql functions.  Here are two techniques for selecting a random value from a pre-defined range of values in a tsql script.  The first technique uses a table variable ( MSSQL 2000 + &#8230; <a href="http://ericfickes.com/2010/01/select-random-value-from-a-range-of-values/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Earlier I blogged about <a title="TSQL UDFs for generating random numbers" href="http://ericfickes.com/2009/09/generate-random-integers-using-tsql-udfs/" target="_blank">creating random numbers using tsql functions</a>.  Here are two techniques for selecting a random value from a pre-defined range of values in a tsql script.  The first technique uses a <a title="MSSQL 2000 let's you create table variables" href="http://msdn.microsoft.com/en-us/library/aa260638%28SQL.80%29.aspx" target="_blank">table variable</a> ( MSSQL 2000 + ), and the second uses a <a title="CTEs in MSSQL 2005 let you build queries a little differently" href="http://technet.microsoft.com/en-us/library/ms175972%28SQL.90%29.aspx" target="_blank">Common Table Expression</a> or CTE ( MSSQL 2005+ ).</p>
<h3>Select a random value using a table variable</h3>
<pre class="brush: sql; title: ; notranslate">

-- var to hold random integer
declare @field_val int

-- create table var to hold value range [ 0, 512, 1024, 2048, 4096 ]
-- inserting the first value sets the structure for the table variable
SELECT 0 AS 'num'
INTO #temp

-- insert data into table var
INSERT INTO #temp VALUES ( 512 )
INSERT INTO #temp VALUES ( 1024 )
INSERT INTO #temp VALUES ( 2048 )
INSERT INTO #temp VALUES ( 4096 )

-- assign random value
SELECT TOP 1 @field_val = num FROM #temp ORDER BY NEWID()

-- show value
SELECT @field_val

-- drop the table variable
DROP TABLE #temp
</pre>
<h3>Select a random value using a CTE</h3>
<pre class="brush: sql; title: ; notranslate">
-- define our data table
WITH data( car )
AS
(
	-- UNION together our range of values
	SELECT 'audi' AS 'car'
	UNION
	SELECT 'bmw' AS 'car'
	UNION
	SELECT 'infinity' AS 'car'
	UNION
	SELECT 'lexus' AS 'car'
	UNION
	SELECT 'porsche' AS 'car'
)
-- select a random value
SELECT TOP 1 car FROM data
ORDER BY NEWID()
</pre>
<p>Both of these techniques can be used with numbers or text.  Just be sure to mind your quotes, and variable datatypes.  Being able to pick a random value in data generation scripts has proven very useful.  I hope this helps somebody else out as well.</p>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2010/01/select-random-value-from-a-range-of-values/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Generate random integers using tsql UDFs</title>
		<link>http://ericfickes.com/2009/09/generate-random-integers-using-tsql-udfs/</link>
		<comments>http://ericfickes.com/2009/09/generate-random-integers-using-tsql-udfs/#comments</comments>
		<pubDate>Wed, 02 Sep 2009 19:55:48 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[database]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[microsoft]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[tsql]]></category>
		<category><![CDATA[integer]]></category>
		<category><![CDATA[random]]></category>
		<category><![CDATA[random integer generation]]></category>
		<category><![CDATA[random number]]></category>
		<category><![CDATA[sql2005]]></category>
		<category><![CDATA[udf]]></category>
		<category><![CDATA[user defined functions]]></category>
		<category><![CDATA[view]]></category>

		<guid isPermaLink="false">http://ericfickes.com/?p=928</guid>
		<description><![CDATA[Ever need to generate random numbers from the integer family?  I had this need on a project so I whipped up these four tsql User Defined Functions to help with this task.  There are four functions in all, one for &#8230; <a href="http://ericfickes.com/2009/09/generate-random-integers-using-tsql-udfs/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Ever need to generate random numbers from the integer family?  I had this need on a project so I whipped up these four <a title="( udf ) CREATE FUNCTION on MSDN" href="http://msdn.microsoft.com/en-us/library/ms186755.aspx" target="_blank">tsql User Defined Functions</a> to help with this task.  There are four functions in all, one for tinyint, smallint, int, and bigint.  Additionally, you will need to create one VIEW since you can not fire the tsql function RAND() inside of a udf.</p>
<p>With these functions, you can generate random integers in their native range.</p>
<pre class="brush: sql; title: ; notranslate"> SELECT dbo.getRandomInt( NULL, NULL ) </pre>
<p>Or you can restrict your random integers to a range of your liking.</p>
<pre class="brush: sql; title: ; notranslate"> SELECT dbo.getRandomInt( 1000, 1000000000) </pre>
<p>Just as a reminder, here are the native ranges for these four<a title="int, bigint, smallint, and tinyint (Transact-SQL)" href="http://msdn.microsoft.com/en-us/library/ms187745.aspx" target="_blank"> integer types as supported by MS SQL Server 2005</a></p>
<table border="1" cellspacing="7" cellpadding="7" rules="rows">
<tbody>
<tr>
<td style="text-align: right;"><strong>bigint</strong></td>
<td>-2^63 (-9,223,372,036,854,775,808) to 2^63-1 (9,223,372,036,854,775,807)</td>
</tr>
<tr>
<td style="text-align: right;"><strong>int</strong></td>
<td>-2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647)</td>
</tr>
<tr>
<td style="text-align: right;"><strong>smallint</strong></td>
<td>-2^15 (-32,768) to 2^15-1 (32,767)</td>
</tr>
<tr>
<td style="text-align: right;"><strong>tinyint</strong></td>
<td>0 to 255</td>
</tr>
</tbody>
</table>
<p>Each of these functions have the same structure and primarily differ only by the integer type&#8217;s native range.  Here is the guts of one of the UDFs in case you want just the facts.</p>
<pre class="brush: sql; title: ; notranslate">/******************************************************************************
Generate a random int
-------------------------------------------------------------------------------
USAGE :
 -- Get random int in the default range -2,147,483,648 to 2,147,483,647
 SELECT dbo.getRandomInt( NULL, NULL )

 -- Get random tinyint within a specific range
 SELECT dbo.getRandomInt( 1000, 30000 )

REQUIREMENT : Since you can't call RAND() inside of a UDF,
this function is dependant on the following VIEW vRand :

-- BEGIN VIEW
 -- This is only a helper VIEW since currently you can not use RAND() in a UDF
 -- DROP VIEW vRand
 CREATE VIEW [dbo].[vRand]
 AS
 SELECT RAND() AS 'number'
-- END VIEW

******************************************************************************/

USE SmartEarth
GO

IF OBJECT_ID (N'getRandomInt') IS NOT NULL
 DROP FUNCTION getRandomInt
GO

CREATE FUNCTION getRandomInt( @min_in int, @max_in int )
RETURNS int
WITH EXECUTE AS CALLER
AS
BEGIN
-------------------------------------------------------------------------------
 DECLARE @max int,
 @min int,
 @rand NUMERIC( 18,10 ),
 @max_big NUMERIC( 38, 0 ),
 @rand_num NUMERIC( 38, 0 ),
 @out int;

 -- define this datatype's natural range
 SET @min = -2147483648    -- -2,147,483,648
 SET @max = 2147483647    -- 2,147,483,647

 -- Check to see if a range has been passed in.
 -- Otherwise, set to default tinyint range
 IF( @min_in is not null AND @min_in &gt; @min )
 SET @min = @min_in

 IF( @max_in is not null AND @max_in &lt; @max )
 SET @max = @max_in
 -- end range check

 -- get RAND() from VIEW since we can't use it in UDF
 SELECT @rand = number FROM vRand

 -- CAST @max so the number generation doesn't overflow
 SET @max_big = CAST( @max AS NUMERIC(38,0) )

 -- make the number
 SELECT @rand_num = ( (@max_big + 1) - @min ) * @rand + @min;

 -- validate rand
 IF( @rand_num &gt; @max )
 -- too big
 SET @out = @max
 ELSE IF ( @rand_num &lt; @min )
 -- too small
 SET @out = @min
 ELSE
 -- just right, CAST it
 SET @out = CAST( @rand_num AS int )

 -- debug
 -- SELECT @min_in AS 'min_in', @max_in AS 'max_in', @min AS 'min', @max AS 'max', @rand, @rand_num AS 'rand_num', @out AS 'out'

 -- return appropriate
 RETURN @out;

-------------------------------------------------------------------------------

END;
GO</pre>
<h3>So where do you get the code?</h3>
<p>You can view all functions and view online at the following <a title="GIST @ GITHUB" href="http://gist.github.com/" target="_blank">gist.github</a> urls:</p>
<ul>
<li><a title="tsql view vRand" href="http://gist.github.com/179910" target="_blank">VIEW : vRand</a></li>
<li><a title="tsql udf getRandomTinyint" href="http://gist.github.com/179904" target="_blank">UDF : getRandomTinyint</a></li>
<li><a title="tsql udf getRandomSmallint" href="http://gist.github.com/179906" target="_blank">UDF : getRandomSmallint</a></li>
<li><a title="tsql udf getRandomInt" href="http://gist.github.com/179907" target="_blank">UDF : getRandomInt</a></li>
<li><a title="tsql udf getRandomBigint" href="http://gist.github.com/179908" target="_blank">UDF : getRandomBigint</a></li>
</ul>
<p>Or you can just <a title="download all the tsql view and functions in a single zip file" href="http://ericfickes.com/code/tsqlRandomIntFunctions.zip" target="_blank">download all the source code in one zip file here</a>.</p>
<p>Hopefully this will help somebody out.  If you&#8217;re a DBA or just a tsql wizard, let me know what you think.  Can I do these functions a better way?  Is this already built into SQL2005 and I just didn&#8217;t know it?  All of this tsql was written against SQL Server 2005, but I&#8217;m pretty sure it would work on SQL2000 and SQL2008 as well.</p>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2009/09/generate-random-integers-using-tsql-udfs/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>I built a calendar in a tSQL SPROC</title>
		<link>http://ericfickes.com/2008/10/i-built-a-calendar-in-a-tsql-sproc/</link>
		<comments>http://ericfickes.com/2008/10/i-built-a-calendar-in-a-tsql-sproc/#comments</comments>
		<pubDate>Tue, 07 Oct 2008 02:48:25 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[SQL]]></category>
		<category><![CDATA[calendar]]></category>
		<category><![CDATA[mssql]]></category>
		<category><![CDATA[sproc]]></category>
		<category><![CDATA[stored procedure]]></category>
		<category><![CDATA[table variables]]></category>
		<category><![CDATA[tsql]]></category>
		<category><![CDATA[tsql date functions]]></category>

		<guid isPermaLink="false">http://ericfickes.com/?p=20</guid>
		<description><![CDATA[Here&#8217;s a blast from the past that I recently found in my archives. It&#8217;s a novelty stored procedure I wrote during my MS SQL 2000 DBA days. Back when I wrote this sproc, I was really big into writing calendar &#8230; <a href="http://ericfickes.com/2008/10/i-built-a-calendar-in-a-tsql-sproc/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a blast from the past that I recently found in my archives.  It&#8217;s a novelty stored procedure I wrote during my MS SQL 2000 DBA days.<br />
Back when I wrote this sproc, I was really big into writing calendar applications.  I have written some sort of calendar application in<br />
almost every language I know, so writing one in tSql made sense to me.</p>
<p>While I never used this sproc in an application, or had any practical use for it, I still think it&#8217;s cool.  It&#8217;s primarily an excercise using<br />
tSql&#8217;s date functions, and my all time favorite feature of MS SQL 2000+, table variables.</p>
<p>If you use MSSQL 2000 or higher and don&#8217;t use table variables, I highly recommend looking into these.  In a nutshell, it&#8217;s a type of tSql variable<br />
that is a table.  You can select, insert, update, and delete the rows in this variable just like it&#8217;s a real table.  The lifespan of a table variable<br />
is the length of your connection to your db.  So if you have a table var #myTable in sprocA, as soon as sprocA completes execution, #myTable is gone.<br />
SprocB can&#8217;t access #myTable unless is specifically creates a new table var by this name.</p>
<p>So I wrote an article about this sproc for a database site years ago and I haven&#8217;t been able to find it again.  This was web1.0 days, so I&#8217;m sure the site<br />
is gone by now.  The good thing is I still have the sproc, and now you can to.</p>
<p>So here&#8217;s the info.  The sproc efCalendar accepts a month number and year number, and spits out two recordsets.</p>
<ol>
<li>Month, Year</li>
<li>Calendar view of that month</li>
</ol>
<p>Recordset 1 is two columns, month name, and year.</p>
<p>Recordset 2 is a calendar view of the specified month.  There is a column for each weekday, starting with Sunday and ending with Saturday.<br />
Then there is a row for each week in the specified month.</p>
<p>Here is what the results look like when run in Query Analyzer.</p>
<div id="attachment_19" class="wp-caption aligncenter" style="width: 509px"><a href="http://ericfickes.com/wp-content/uploads/2008/10/sproc-efcalendar.gif" rel="lightbox[20]"><img class="size-full wp-image-19" title="sproc-efcalendar" src="http://ericfickes.com/wp-content/uploads/2008/10/sproc-efcalendar.gif" alt="tSQL calendar sproc" width="499" height="370" /></a><p class="wp-caption-text">tSQL calendar sproc</p></div>
<p><a title="eric fickes loves mssql's table variables and sprocs" href="http://ericfickes.com/wp-content/uploads/2008/10/create_procedure_efcalendar.sql" target="download tsql calendar stored procedure">Download the efCalendar sproc here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2008/10/i-built-a-calendar-in-a-tsql-sproc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Create comma seperated list out of a sql query ( tsql )</title>
		<link>http://ericfickes.com/2006/06/create-comma-seperated-list-out-of-a-tsql-query-tsql/</link>
		<comments>http://ericfickes.com/2006/06/create-comma-seperated-list-out-of-a-tsql-query-tsql/#comments</comments>
		<pubDate>Thu, 22 Jun 2006 14:50:00 +0000</pubDate>
		<dc:creator>Eric Fickes</dc:creator>
				<category><![CDATA[fun]]></category>
		<category><![CDATA[microsoft]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[coalesce]]></category>
		<category><![CDATA[microsoft sql server]]></category>
		<category><![CDATA[mssql]]></category>
		<category><![CDATA[tsql]]></category>

		<guid isPermaLink="false">http://ericfickes.com/2006/06/22/76/</guid>
		<description><![CDATA[Surfing the net for a sql answer, I came across something really cool. Below is an example of how to create a comma separated list of values in a single query. The results should look something like this]]></description>
			<content:encoded><![CDATA[<p>Surfing the net for a sql answer, I came across something really cool. Below is an example of how to create a comma separated list of values in a single query.</p>
<pre class="brush: sql; title: ; notranslate">
–declare holder var
DECLARE @list VARCHAR(8000)

–build comma separated list
SELECT @list = COALESCE(@list + ‘, ‘, ”) + CAST(track_id AS VARCHAR(5) )
FROM webtool_tracks

–show results
SELECT @list AS ‘list’
</pre>
<p><span style="color: #000000;">The results should look something like this</span><br />
<a href="http://photos1.blogger.com/blogger/1587/58/1600/coalesce.jpg" onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" rel="lightbox[76]"><img style="FLOAT: left; MARGIN: 0pt 10px 10px 0pt; CURSOR: pointer" src="http://photos1.blogger.com/blogger/1587/58/320/coalesce.jpg" border="0" alt="" /></a><br />
<span style="color: #ff0000;"><br />
</span></p>
]]></content:encoded>
			<wfw:commentRss>http://ericfickes.com/2006/06/create-comma-seperated-list-out-of-a-tsql-query-tsql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

