<?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>Internets, Databases, Skateboards, Ice Hockeys, and Family</description>
	<lastBuildDate>Thu, 22 Jul 2010 22:45:33 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<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 want to PIVOT against a varchar column?  If you&#8217;ve been in this need you know [...]]]></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;">
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;">
/*
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>0</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, as opposed to inline with your other @variables. Typically in my sprocs or sql scripts [...]]]></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>0</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[random]]></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 this is a new concept. Running this query SELECT * INTO #myTableVar FROM YourTable Gives [...]]]></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;">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;">
// 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;">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;">
-- 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;">
-- #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;">
-- 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[random]]></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[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 + ), and the second uses a Common Table Expression or CTE ( MSSQL 2005+ ). [...]]]></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;">

-- 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;">
-- 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[utility]]></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 tinyint, smallint, int, and bigint.  Additionally, you will need to create one VIEW since you [...]]]></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;"> 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;"> 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;">/******************************************************************************
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>3</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 applications. I have written some sort of calendar application in almost every language I know, [...]]]></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. –declare holder var DECLARE @list VARCHAR(8000) –build comma separated list SELECT @list = COALESCE(@list + ‘, ‘, ”) + CAST(track_id AS VARCHAR(5) ) FROM [...]]]></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;">
–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>
