The primary key of my database (SQL server 2005) table is a uniqueidentifier.
I am using the following code to insert a row into my table:
myCommand.CommandText = sqlEvent.ToString(); //add the sql query to the command
myCommand.Connection = this.dbConnection; //add the database connection to the command
myCommand.ExecuteNonQuery(); //execute the insert query
I need to retrieve the GUID that is automatically generated when the insert command is executed.
Can someone help me? How do I get the GUID that is automatically generated? I have tried lots of things like using
string _id = (string)myCommand.ExecuteScalar();
and I am still stuck. I will really appreciate it if someone can refer me to some code sample.
HELP
Here is a sample:
CREATE TABLE T1(
id uniqueidentifier PRIMARY KEY DEFAULT(NEWID()),
name nvarchar(100)
);
INSERT INTO T1 (name) OUTPUT inserted.id VALUES('name 1');
SELECT * from T1;
So you just need to call T-SQL similar to "INSERT INTO T1 (name) OUTPUT inserted.id VALUES('name 1');" with ExecuteScalar();
Thanks,
Zuomin
No comments:
Post a Comment