Showing posts with label uniqueidentifier. Show all posts
Showing posts with label uniqueidentifier. Show all posts

Wednesday, March 28, 2012

Return a UNIQUEIDENTIFIER

Hi,

I am writing a C# application that uses a SQL server database to hold its data. I need to create a stored procedure that returns a particular row's primary key value. This is no problem if the primary key is an INT. But my primary key is a unique identifier, and the stored procedure doesn't want to let me return any values that aren't INTs. Can someone please tell me how to get around this?

Thanks in advance.

ScottYou'll have to declare it as an outparameter.
And if you want something easier to handle you can convert it to
a varchar using CONVERT(myguid,VARCHAR)

Regards
Fredr!k|||Fredrik2000,

Thank you so much. That is exactly what I needed. Also, for anyone else out there, it is actually in the format:

CONVERT(VARCHAR(36), myguid)

where of course 36 is the number of characters allocated for the datatype.

Sc0tt|||Ahh, I always get the order mixed up (didn't have a copy of books online at the computer
I'm posting from...)

Nice to hear you got it working.

Regards
Fredr!k

Tuesday, March 20, 2012

Retrieving GUID from INSERT query -- HELP

I have tried many code sample but I am very stuck

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