Thursday, February 22, 2007

Get the value of the identity column after inserting a record

Aparently there are still a lot of people who are having problems when inserting rows in a table that has an identity field. Sometimes you need to have the id of the record you just inserted to be able to use it afterwards.

Yesterday I saw someone doing a SELECT MAX(id) FROM MyTable to be able to get the maximum id and then raise it by 1. This gives 2 issues:

  • what if someone else has added a row after you selected the maximum value?
  • what if the identity increment is not 1?

In SQL Server there is a function SCOPE_IDENTITY() that returns the last used identity within the scope of the statement. If you add this to the end of your statement, you can return the value of the identity column.

Here is a sample that shows you how to do it (NOTE the end of the select statement):

static void Main(string[] args)
{
int identity = -1;
string connectionString = "Data Source=LP51; Initial Catalog=Northwind; User Id=sa; Password=P@ssw0rd;";
string sql = "INSERT INTO Employees (LastName, FirstName) VALUES (@LastName, @FirstName) SELECT SCOPE_IDENTITY()";

SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@LastName", "Verhoeven");
cmd.Parameters.AddWithValue("@FirstName", "Geert");


try
{
conn.Open();
identity = int.Parse(cmd.ExecuteScalar().ToString());
}
catch
{
// implement exception handling here
}
finally
{
conn.Dispose();
cmd.Dispose();
}


Console.WriteLine("The identity is {0}", identity);
Console.WriteLine("Press any key to continue ...");
Console.ReadLine();
}

Wednesday, February 14, 2007

"This database does not have a valid dbo user ..." message when creating database diagrams

When you try to create a database diagram on a SQL Server 2005 database, it happens that you receive the following message:


This database does not have a valid dbo user or you do not have permissions to impersonate the dbo user, so database diagramming is not available. Do you want to make yourself the dbo of this database in order to use database diagramming?

When you click Yes, you sometimes also receive the following message:


This database does not have a valid dbo user or you do not have permissions to impersonate the dbo user, so database diagramming is not available. Ensure the dbo account is valid and ensure you have impersonate permission on the dbo account.


NOTE: This message can also show up when you access the database diagrams while using a domain account and are disconnected from the network.

The problem is the owner of the database.

Here is a procedure to fix the issue:

  • Install the "Microsoft SQL Server Management Studio Express" (link)

  • Close all the connections to the database

  • Open the Microsoft SQL Server Management Studio Express and connect to your SQL Server Express instance

  • Right click the Databases folder in the Object Explorer and click Attach...

  • Browse to the .mdf file of your database and click Ok

  • Open the Properties page of the database and select the Files tab


  • In the files tab, you can see that the Owner is not filled in.
    Select your account as owner and click Ok.

This should do the trick.

Saturday, February 10, 2007

Checked and Unchecked keyword

When reading an article I noticed the checked keyword for the first time.

The checked and unchecked keywords are used to control the overflow-checking for integral-type arithmetic operations and conversions. It can be used as an operator or a statement.

In a checked context, if an expression produces a value that is outside the range of the destination type, an exception will be thrown.

In an unchecked context, if an expression produces a value that is outside the range of the destination type, the value will be truncated.

The following sample shows the use of the checked keyword which forces an exception when an overflow occurs:
static void Main(string[] args)
{
int x = int.MaxValue;
int y = int.MaxValue;
int z = 0;

try
{
// Checked in its statement form:
checked
{
z = x + y;
}
}

catch (System.OverflowException e)
{
Console.WriteLine(e.Message);
}

Console.WriteLine(z.ToString());
Console.ReadLine();
}

Result:
Arithmetic operation resulted in an overflow.
0


The following sample shows the use of the unchecked keyword which truncates the result when an overflow occurs:


static void Main(string[] args)
{
int x = int.MaxValue;
int y = int.MaxValue;
int z = 0;

try
{
// Unchecked in the operator form:
z = unchecked(x + y);
}

catch (System.OverflowException e)
{
Console.WriteLine(e.Message);
}

Console.WriteLine(z.ToString());
Console.ReadLine();
}


Result:
-2

REMARKS: If neither checked nor unchecked is used, a constant expression uses the default overflow checking at compile time, which is checked. Otherwise, if the expression is non-constant, the run-time overflow checking depends on other factors such as compiler options and environment configuration.

Friday, February 2, 2007

Passed the 70-441 exam

This morning I finally passed the Microsoft SQL Server 2005 Database Solutions Design (70-441) exam!

In total I received 56 questions based on 5 different scenario's.

To study the exam, I used the SYBEX - MCITP Developer: Microsoft SQL Server 2005 Database Solutions Design Study Guide (Exam 70-441) book. The book covers the exam really good and is a good book to use as a reference.