Hey, I rewrote UNION by way of UNPIVOT

Yesterday a team mate of mine asked me to review a piece of SQL script that looked like a good candidate for UNPIVOT. Below is the amended version of that code (I obfuscated the data and added a simple data initialization using the WITH clause): ;with u as ( -- data setup select * from ( values(1, 1, 1, 1), (2, 1, 1, 0), (3, 1, 0, 0), (4, 0, 0, 0) ) t(UserID, HasDbSkills, HasBackendSkills, HasFrontEndSkills) ) select * from ( select UserID, 0 as SkillType, 1 as DevelopmentSkill from u where HasDbSkills = 1 union select UserID, 1 as SkillType, 1 as DevelopmentSkill from u where HasBackendSkills = 1 union select UserID, 2 as SkillType, 1 as DevelopmentSkill from u where HasFrontEndSkills = 1 ) t(UserID, SkillType, DevelopmentSkill) order by UserID, SkillType Indeed, after a quick analysis, this script turned out to be ripe for UNPIVOT:

CREATE DATABASE (SMO)

Create a SQL Server Database by using SMO

In this small tutorial I will show you how to create a database with SMO and C# in Visual Studio 2008. I will use a Console application.

Prerequisites:

  1. SQL Server 2005 is installed
  2. Visual Studio 2008 is installed

Code

Assemblies
Your C# project must reference:
  1. System
  2. System.Data
  3. Micrososft.SqlServer.ConnectionInfo
  4. Micrososft.SqlServer.Management.Sdk.Sfc
  5. Micrososft.SqlServer.Smo
Namespaces
The source class file must use:
  1. System
  2. System.Data.SqlClient
  3. Micrososft.SqlServer.Management.Common
  4. Micrososft.SqlServer.Management.Smo
class ConsoleSmo
{
  public static Main()
  {
    string connLocal = "Data Source=(local); Integrated Security=SSPI;"
    SqlConnection connection = new SqlConnection(connLocal);
    Server server = new Server(new ServerConnection(connection));
    Database db = new Database(server, “TestDb”);
    db.Create();
    connection.Close();
  }
}
Explanations
This code opens the connection to the server and produces the Server object. Next, it creates the database. Finally, it closes the connection. The last step is very important, because otherwise the connection object will not be returned to the connection pool (read about the connection pooling at MSDN).

Comments

Popular posts from this blog

Initializing xslt variable with static content