Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct use of SCOPE_IDENTITY function within simple stored procedure

I'd like to simply send some information from a simple client to a log file and then use the identity created for further processing.

Is the following use of SCOPE_IDENTITY() correct?

CREATE PROCEDURE [dbo].[LogSearch]
    @userName       VARCHAR(50),
    @dateTimeStart  DATETIME        
AS
BEGIN
SET NOCOUNT ON;


    INSERT INTO [WH].[dbo].[tb_Searches]
            (
            [UserName],
            [DateTimeStart]
            )
    SELECT  @userName, 
        @dateTimeStart;

    SELECT SCOPE_IDENTITY() AS ProfileKey;

END;

EDIT

I've edited code to the following:

ALTER PROCEDURE [dbo].[LogSearch]
    @userName   VARCHAR(50),
    @dateTimeStart  DATETIME
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO [WH].[dbo].[tb_Searches]
            (
            [UserName],[DateTimeStart]
            )
    VALUES  (@userName, @dateTimeStart);

    RETURN SCOPE_IDENTITY();

END;
like image 808
whytheq Avatar asked Mar 23 '13 20:03

whytheq


1 Answers

Seems like this is the best approach - can see a few references advising to only use RETURN as a way of communicating state or errors so an OUTPUT parameter is better practice:

ALTER PROCEDURE [dbo].[LogSearch]
    @userName      VARCHAR(50),
    @dateTimeStart DATETIME,
    @searchID      INT OUTPUT
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO [WH].[dbo].[tb_Searches]
                (
                UserName,
                DateTimeStart
                )
    VALUES  
                (
                @userName, 
                @dateTimeStart
                );

    SET @searchID = SCOPE_IDENTITY();

END;
like image 91
whytheq Avatar answered Oct 26 '22 04:10

whytheq