Retrieve assigned GUID from SQL insert

When inserting into a Sql table with a Guid assigned using the default of NEWID() you cannot use ‘SCOPE_TO_IDENTITY’ to return the Guid you’ve been assigned into you application (like you would to retrieve an integer ID). It doesn’t work for Guids because they’re not number values and thus cannot be an identity field. The answer was to retrieve the Guid using the following query, for a table that has a column nameĀ TableNameGuid and ColumnName:


INSERT INTO TableName (ColumnName)
OUTPUT inserted.TableNameGuid
VALUES (Value)

The key part to this is the OUTPUT, its what returns the value. Then in the C# code I would call something like


using (SqlCommand cmd = new SqlCommand(yourSqlQueryString, connection))
{
     connection.open();
     Guid assignedGuid = (Guid)cmdCheck.ExecuteScalar(); //gets the guid
     connection.Close();
}

Which assigns your new, freshly created, Guid to the variable assignedGuid.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s