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))
     Guid assignedGuid = (Guid)cmdCheck.ExecuteScalar(); //gets the guid

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