Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server: Return uniqueidentifier from stored procedure

Can I return UNIQUEIDENTIFIER from a stored procedure using the RETURN statement or is it only by using the OUTPUT statement?

i.e to return the PersonID UNIQUEIDENTIFIER:

CREATE PROCEDURE CreatePerson
    @Name NVARCHAR(255), 
    @Desc TEXT
AS
DECLARE @Count INT
DECLARE @JobFileGUID UNIQUEIDENTIFIER 

-- Check if job exists?
SET @Count = (SELECT COUNT(Name) AS Name FROM Person WHERE Name=@Name)

IF @Count < 1
BEGIN
    SET @PersonGUID = NEWID();

    INSERT INTO Person 
        (PersonID, Name, [Desc]) 
        VALUES (@PersonGUID, @Name, @Desc)

END

    SELECT @PersonGUID = Person.PersonID 
    FROM Person
    WHERE Name = @Name

    RETURN @PersonGUID
GO

Thanks

like image 844
Belliez Avatar asked Jan 11 '10 09:01

Belliez


People also ask

How do I get Uniqueidentifier in SQL Server?

SQL Server NEWID to Generate GUID Type the below code in SSMS and execute. DECLARE @guid uniqueidentifier = NEWID(); SELECT @guid as 'GUID'; Here we created a variable named guid of data type uniqueidentifier.

What data type is Uniqueidentifier SQL Server?

The globally unique identifier (GUID) data type in SQL Server is represented by the uniqueidentifier data type, which stores a 16-byte binary value. A GUID is a binary number, and its main use is as an identifier that must be unique in a network that has many computers at many sites.

How do I get the last inserted GUID in SQL Server?

Just between the Insert section and Values keyword. There is a query statement to output the inserted Guid into the variable table. Then to get the value itself you can see the last query where we select the ColGuid from the variable table.

How add Uniqueidentifier column in SQL?

If the table you want to edit participates in replication or offline mapping or contains a GUID, you must insert a unique value to the global ID or GUID column when you insert a new record to the table using SQL. To do this, you can use the newid() function.


1 Answers

In stored procedure - only using the OUTPUT statement. In function - return.

like image 108
Tadas Šukys Avatar answered Oct 13 '22 11:10

Tadas Šukys