// end sketch
Tag Archives: exec
Today I took 30 minutes to save hours
UPDATE – 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 time to go command line with all of this.
Here the contents of my batch file.
### DELETE TEMP FILES del /q /f /s Z:_FavoriteClient_GIT_webappinvoices* /f /s ### RESTORE DATABASE sqlcmd -S "localhost" -i Z:_FavoriteClient_GIT_sqlrestoreBackup.sql
To use this in a .bat file, copy and paste the text into Notepad, then save as “restore.bat”. Remember, you will need to wrap your filename.bat with quotes, otherwise Notepad will save the file as filename.bat.txt.
* The contents of restoreBackup.sql is listed below.
One of my favorite pastimes as a programmer is writing code that writes code, aka workflow automation. It’s not something I do on every project, but I’ve been doing a lot of SQL Server development recently, and I’ve been having a lot of fun using the INFORMATION_SCHEMA views to build VO classes, forms representing tables, or just finding what tables have a specific column. Today I took a 30 minute trip to the SYS side and wrote a tsql script that will save me hours.
The web application I’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 ).
I thought about a handful of options, and ended up going with this solution.
- Setup all test transactions in web application by hand ( get the data ready )
- Take a full database backup ( freeze the data )
- Use TSQL script to drop all connections to my app’s db, then restore the database to the “testable” state from step 1 ( reset the DB )
Here is my TSQL script
[sql]
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:DBBackupDA413.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
[/sql]
A few notes about this script :
- I only need to disconnect my web application’s database user, not any user
- I’m using the latest full backup, and not a specific database snapshot
- The SPROC kill doesn’t like @variables as input, so use EXEC
- Your web server doesn’t know the user was disconnected, so you’ll have to log back into your application.
- 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 )
- If you’re not the only person connected to this database, make sure you don’t disconnect anybody else using the same database name
This solution is perfect for me because I have full control over my code, database, and server. It’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’s probably best used as reference for others. However, this technique of rolling back the database could be applied to any software application using SQL Server for it’s datasource.
Hope this helps somebody.
What if you want to PIVOT against a text column?
If you’ve ever worked with or researched SQL Server’s PIVOT function, you probably noticed most of the samples pivot against an id column. Typically an int column like EmployeeID, or StoreID. That’s fine and dandy, but what happens when you want to PIVOT against a varchar column? If you’ve been in this need you know this is a bit of a task.
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 DatabaseLog table in the AdventureWorks sample database to return a count of Events logged for each Schema. Before jumping into the PIVOT, here’s a simple query that gives you the same information, all Schemas, Events, and Event counts.
SELECT [Schema], [Event], COUNT( [Event] ) AS 'event_count' FROM DatabaseLog GROUP BY [Schema], [Event] ORDER BY [Schema]
Running this query should give you a long result looking something like this.
While this query returns the same information to you, I don’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.
Now let’s have a look at retrieving the same information using the PIVOT function.
/*
Example of a dynamic PIVOT against a varchar column from the Adventureworks database
References :
PIVOT & 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
Assuming you have the AdventureWorks database installed on your server, running this sql should give you a result looking something like this.
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.
A quick explanation of what’s happening in this sql
- First you fill a table variable ( #events ) with all Events from DatabaseLog
- Next create a comma delimited list of the Events inside of the table variable
- Drop the table variable now that we’ve got our delimited list of Events
- Build the PIVOT statement as a string so you can inject the Events list
- Fire the dynamic SQL via EXEC
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’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.
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’s pretty simple. I hope this makes sense, and if you have any suggestions of better techniques, I’d love to hear it.
What happens in EXEC, stays in EXEC. Lifespan of a MSSQL table variable
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’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 you a new table variable named myTableVar. Table variables are scoped to the active connection, so running this will work.
// 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
However, let’s say you have an aspx page or a sproc that runs this query.
SELECT * INTO #myTableVar FROM YourTable
You can not access myTableVar in a separate connection to the database because as soon as the first query’s connection closes, myTableVar gets dropped. Here are a few other scenarios that also demonstrate the scoping of a table variable.
-- FAILS
EXEC ('SELECT * INTO #tmp FROM MyTable;');
-- #tmp does not exist
SELECT * FROM #tmp
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.
-- #tmp2 works inside of EXEC statement
EXEC ('SELECT * INTO #tmp2 FROM MyTable; SELECT * FROM #tmp2');
Here #tmp2 works because it’s being used inside of the EXEC statement. This is worth knowing if you work with dynamic sql statements and exec.
-- works! SELECT * INTO #tmp FROM MyTable; -- #tmp exists SELECT * FROM #tmp
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.





