Here is a quick guide to get the new value of NEWSEQUENTIALID() when inserting a row into a table in ms sql. If you have attempted to use NEWSEQUENTIALID() before you will know that it is only possible to use as a generated value in the table when the row is being inserted. This is a guide to get this value from c# when inserting the row. For this method we are going to be using the OUTPUT clause in the INSERT statement.
We will start with a really basic table in ms sql. Runt he following to create it.
CREATE TABLE ATable (
ATableID uniqueidentifier DEFAULT NEWSEQUENTIALID(),
To insert a row we need some simple sql. Except in this case while we are inserting the row we can also output the value that is created during the insert from ms sql. Some sample sql todo this is below.
INSERT INTO ATable (Data) OUTPUT inserted.ATableID
So if you run that you will be returned some results. For my example I got 'DCAEFDBD-793F-E011-822D-003067017B97' back in the results pane.
Todo this in c# it will work much the same. Though to get the value back you use the ExecuteScalar command on the SqlCommand. An example is below.
static void Main(string args)
DBConn Conn = new DBConn("Data Source=SQL;Initial Catalog=Testing;Integrated Security=True;Connect Timeout=30;Timeout=120");
SqlCommand sql = new SqlCommand(@"
INSERT INTO ATable (Data) OUTPUT INSERTED.ATableID
for (int i = 0; i < 10; i++)
string tmp = Conn.ExecuteScalar(sql).ToString();
This nice thing about this when being used is that it will help prevent index fragmentation and page splits occuring on the index while is using the unique identifier. So the sample output of the Table will be as follows.