Return Primary Key After Insert Into Database

There have been a few times that it has been necessary to return an auto-generated primary key after an insert into a database.  This is a tidbit of MS SQL Server code that will do just that:

cmd.CommandText = string.Format("INSERT INTO Areas(Name) VALUES('{0}'); SELECT SCOPE_IDENTITY()", Manager.SQLSafe(_name)); _id = Convert.ToInt32(cmd.ExecuteScalar());

As you can see, this will return you an integer value that represents the primary key of a row inserted into a database.

Print | posted on Saturday, December 30, 2006 11:31 PM

Comments on this post

# re: Return Primary Key After Insert Into Database

Requesting Gravatar...
you could use:
cmd.CommandText = string.Format("INSERT INTO Areas(Name) VALUES('{0}') RETURNING id);

_id = Convert.ToInt32(cmd.ExecuteScalar());
Left by joeb on Dec 16, 2011 1:25 PM

Your comment:

 (will show your gravatar)
 
Please add 1 and 2 and type the answer here: