SQL Server
FIX: Failed to Generate a User Instance …
Jan 10th
I generate my databases on the fly while using Active Record.
Every time I start a new project and fire up the app to auto-gen the SQL Express DB I get this error:
Failed to generate a user instance of SQL Server due to failure in retrieving the user’s local application data path. Please make sure the user has a local user profile on the computer. The connection will be closed.
… and it drives me nuts. I work on a project just long enough to forget what I did to fix that error. I’m going to document it here.
The reason this is happening is because the user instance that I’m running IIS under does not have the proper credentials. You can fix this by creating a new app pool in IIS, and having it run under a user that has the rights to create a db (most likely your own account). What I do is create an AppPool called “PrivilegedAppPool” and have it run under my own account. Then restart IIS and you should be able to create your db on the fly.
Presto. No more errors.
DB2 / SQL SERVER 2005 / .NET
Aug 22nd
For those of you who are lucky enough to work with DB2 and .NET, you’re probably already aware that you can run into some issues if you’re not using the correct DB2 Driver.
I’ve been writing some SSIS packages that move some data from a DB2 environment into a SQL Server 2005
Database. I also had to write a few .NET applications that spoke to the DB2 database. Here’s a couple drivers that I used and some of the notes regarding them. I’ve also included a few links that help in regards to development.
Drivers
- Microsoft OLE DB2: DB2OLEDB Driver
- This driver is part of the Feature Pack for SQL Server 2005.
- This Driver worked for most of the time until I needed to work with Large Objects (BLOB/CLOB). Unfortunately I found this after I did a bunch of work –
- “The OLE DB Provider for DB2 does not currently support the DB2 Large Object (LOB) types.” - Distributed Query Support Using the OLE DB Provider for DB2
- IBM DB2 Driver for ODBC and CLI
- Please note, I COULD NOT get the IBM web site to work with IE7. I had to use Firefox to download the file.
- Link Name: IBM DB2 Driver for ODBC and CLI
- File Name: v9fp2_win_db2driver_for_odbc_cli.zip
- Download the file, install and you’ll have the drivers on your machine.
- The thing is, this worked great for the BLOB/CLOB fields, but when the SSIS Package went to transform the DateTime fields it complained about data loss because DB2 has more DateTime precision than SQL Server 2005.
- This was solved by using the Microsoft OLE DB2 Provider as it did not complain about the DateTime. The team I worked with knew that we’d lose some millionths of a second, but that was acceptable for the project. Basically the Microsoft Provider didn’t complain about it like the DB2 provider did. The data came through the conversion correctly, so we were fine with it.
- Please note, I COULD NOT get the IBM web site to work with IE7. I had to use Firefox to download the file.
Other Useful Information/Tools
- SQLState Error Message Reference
- Sometimes SSIS can throw some nasty HRESULT errors your way and you’re left scratching your head trying to figure out what went wrong. If the message includes a SQLState, look in this reference, it will probably be in here, or will point you in the right direction.
- WinSQL Lite
- I like to say its like the SQL Management Studio for DB2. A very nice GUI that allows you to interact with the DB2 system. A lot of “old schoolies” (as I call them) like to use the command line to hammer away at DB2. Me? I like to look at the GUI when I’m looking at tabular data. This tool will make your life 10 times easier when looking for data anomalies.
Returning XML Data as a Record Sets through the CLR in SQL Server 2005
Jul 27th
The Problem
I needed to write something like this …
SELECT * FROM CustomerTest WHERE Customer_Id = 1;
The data returned needed to return the row as well as the data inside of the XML Column in that row, in the same set. (The data in the XML column needed to be returned as sets of records as well.) The XML Contained was simple XML that looked like this:
(click for larger image)
The XML Column was called “Extra_Info”. This is where the above XML was stored.

Ok, lets get to the point… here’s what its supposed to look like when the query is run:
(click for larger image)
A little more about the problem domain..
Awhile back I had a client who wanted to store data in an XML Field, but the XML for each row could be extremely different in each row. One row might have a XML Document that has 1 set of data, while the next might have 10. These XML documents that were being stored did not share a common schema — not at all. But we needed to return the data in an SQL Query or SPROC that would allow the user to view the data as if it were tables in the database.
Solution
So how do we do that with one Query?
Easy - SQL CLR Integration.
We can create a CLR Stored Procedure to do this for us.
Here are the steps the CLR SPROC will go through to return the data.
- Query the DB for the record.
- Get the XML from the column.
- Load the XML into a DataSet object.
- Send the original record results of the row to the client.
- Create record sets off of the DataSet using SqlDataRecord object.
- Send each record back to the client.
Code time baby…
using System; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using Microsoft.SqlServer.Server; using System.IO; using System.Collections.Generic; using System.Data.Common; using System.Xml; public partial class StoredProcedures { [Microsoft.SqlServer.Server.SqlProcedure] public static void TestProcedure(SqlInt32 recordId) { DataSet dataset = null; using (SqlConnection connection = new SqlConnection("context connection=true")) { string xml = string.Empty; using (SqlCommand command = new SqlCommand("SELECT * FROM dbo.CustomerTest WHERE Customer_Id = @recordId")) { command.Parameters.Add(new SqlParameter("@recordId", recordId)); command.Connection = connection; if (connection.State != ConnectionState.Open) { connection.Open(); } using (DbDataReader reader = command.ExecuteReader()) { if (reader.Read()) { xml = reader["Extra_Info"].ToString(); // Load in the XML. XmlReader xmlReader = new XmlTextReader(xml, XmlNodeType.Document, null); dataset = new DataSet(); dataset.ReadXml(xmlReader); } } SqlContext.Pipe.ExecuteAndSend(command); } } if (dataset != null) { foreach (DataTable table in dataset.Tables) { // Set up the record List<SqlMetaData> metaData = new List<SqlMetaData>(); foreach (DataColumn column in table.Columns) { metaData.Add(new SqlMetaData(column.ColumnName, SqlDbType.Variant)); } SqlDataRecord record = new SqlDataRecord(metaData.ToArray()); // Mark the begining of the result-set. SqlContext.Pipe.SendResultsStart(record); foreach (DataRow row in table.Rows) { foreach (DataColumn column in table.Columns) { record.SetValue(table.Columns.IndexOf(column), row[table.Columns.IndexOf(column)]); } // Send the row back SqlContext.Pipe.SendResultsRow(record); } // Mark the end of the result-set. SqlContext.Pipe.SendResultsEnd(); } } } }
Code Review
The sproc is created with the code above.
If we find a record we load the xml into a variable and then load the DataSet with the XML using the ReadXml Method of the DataSet.
if (reader.Read()) { xml = reader["Extra_Info"].ToString(); // Load in the XML. XmlReader xmlReader = new XmlTextReader(xml, XmlNodeType.Document, null); dataset = new DataSet(); dataset.ReadXml(xmlReader); }
Next, we loop through each data table and each record in the data table to create a SqlDataRecord. To build an SqlDataRecord we need a Record definition.These record definitions are defined as SqlMetaData objects. Therefore we need populate an array of SqlMetaData objects by looping through the columns to get the column information. At this point we’re building the columns in which the data will exist in.
// Set up the record List<SqlMetaData> metaData = new List<SqlMetaData>(); foreach (DataColumn column in table.Columns) { metaData.Add(new SqlMetaData(column.ColumnName, SqlDbType.Variant)); } SqlDataRecord record = new SqlDataRecord(metaData.ToArray());
From here, we will build the actual records. This is done by the following method:
- Inform the context that we’re going to begin sending a record by using the SendResultsStart method of the Pipe class.
- When a record is built, we want to send it to the client by calling the SendResultsRow method. This sends the row to the client. We will do this for each record built.
- After the records have been sent we want to tell the client we’re done sending records for this set. We do this by calling the SendResultsEnd method.
This happens for each DataTable in the DataSet. And then finally the results are sent back to the client.
Resolution
Once deployed, the sproc (which I’ve named “TestProcedure”) will show up under the StoredProcedures area of SQL Server, as shown here:
And now you have a stored procedure that will return results of the row as well as the data that is in the XML column, all in the same result set.
Uses: You could use this as an extensibility point in your application by allowing users to add custom fields to the application at run time and then storing the application fields and field data in an XML file which is stored in an SQL Server column. Think of it as a database inside of a database. You could then use it to query the row/column to get the results into a readable form for Crystal or Reporting Services.
Blogs, Podcasts and Screencasts
May 25th
UPDATE: I added the publications I also read at the bottom.
I’ve been asked what blogs I read, podcasts I listen to and screencasts I watch. So here’s a comprehensive list for ya’ll.
Blogs (in no particular order)
- Scott Hanselman
- Jeff Atwood
- Martin Fowler
- Jeremy D. Miller
- K. Scott Allen
- Mads Kristensen
- Sahil Malik
- Roy Osherove
- Jean-Paul S. Boodhoo
- Bil Simser
- Dino Esposito
Then at times I’ll browse the MSDN Blogs. Also note, these are what I call my “essential” blogs. I read these daily. I have about 30 other blogs that I read if I have time.
Podcasts (in no particular Order)
- .NET Rocks
- Hanselminutes
- ARCast with Ron Jacobs
- Polymorphic Podcast
- this Week in Tech
- Agile Talk
- Agile Toolkit Podcast
- Confessions of an Agile Activist
- Lean Agile Straight Talk
- Microsoft Technet Podcasts
- Nitobis Enterprise AJAX Podcast
Other Podcasts I listen to when I can
Simplifying Database Modeling in Visio 2002/2003 through SQL Generation
May 11th
During the development of any new greenfield project you’re going to probably need to interact with a datastore.
From my experience, 8 out of 10 times this is going to be a database acting as the datastore, and in my case, it’s normally SQL Server.
Database Modeling
When in the design phase we’re modeling. Creating a representation of what we’re going to build. In the design of a database I use Visio to do this by building an ERD Diagram.
If you’re like me you’re still probably using Visio 2002/2003. If you’re also like me, you don’t have the Enterprise Architect version of Visio that allows you to forward engineer the database from the ERD Diagram that you’ve created.
So, therein lies a problem. I have to design my database in Visio, then manually create the SQL and run it in query analyzer to get my database. Seem’s like double the work to me.
1. Create the diagram and all the types and relationshiops
2. Copy it by hand into SQL Server Management Studio or the Query Window
I’ve always felt that Microsoft should have included forward engineering for Visio, regardless of the version. Unfortunately they didnt feel the same way.
Model to SQL 
Fortunately there is a solution. A company called Orthogonal Software has a Visio plug-in called Orthogonal Toolbox that will allow you to export the data from the Visio document to an XML File.
Orthogonal has provided a couple XSLT’s that you can apply (look for XSLT on that page). One of which has been altered to export SQL.
The XSLT file that originally was found with the product exported the SQL into one long string. No line breaks, nothing. Just a long string. After some futz’n around with the XSLT I was able to format the SQL that was transformed into readable SQL.
For example, a XSLT generated SQL Code that looks like this:
CREATE TABLE dbo.Employee(
[Employee_Id] bigint NOT NULL,
[Name] nvarchar(100) NOT NULL
);
GO
How to implement
1. Download Orthogonal Toolbox and install it.
2. Create your Visio ERD Diagram.
3. Click the Orthogonal Toolbox Button in the toolbar.
4. Export to XML.
5. Put the XSLT files (download at the bottom of this post) into the same file as the XML File.
6. Open the newly created XML File and add this line after the XML Definition.
<?xml-stylesheet type=”text/xsl” href=”ERD-SQL2005.xslt”?>
6. Open the XML file in Internet Explorer
7. Copy/Paste what you see into Query Analyzer and run.
Thats it. You’ve now gone from Database ERD Model to SQL Code in a few quick steps. TONS of time saved.
Update for SQL Server 2005
The original XSLT was for use with SQL Server 2000. Schemas were not supported in 2000, therefore everything started with “dbo”. To get around this, I reworked the XSLT and changed it to use the table name.
When I’m designing for a SQL Server 2005 database I’ll give my tables names such as [My_Schema].[Table_Name]. Therefore when I export and apply my XSLT, the new exported SQL will look like this:
CREATE TABLE [HumanResources].[Employee](
[Employee_Id] bigint NOT NULL,
[Name] nvarchar(100) NOT NULL
);
GO
Where “HumanResources” is the schema and “Employee” is the table name.
Downloads
2000and2005XSLTs.zip (2.96 KB)