<?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; exec</title>
	<atom:link href="http://ericfickes.com/tag/exec/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>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>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>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>
	</channel>
</rss>

