Skip to content
Advertisement

Stored Procedure return default value?

in my database, there is a Stored Procedure with INSERT INTO statement. The problem is I want this stored procedure will return the StudentCode default value, I think it’s impossible to use the SELECT TOP 1 statement to get this value because there may be multiple rows inserted at the same time. Any help or suggestions?. Thanks very much

ALTER PROC [dbo].[AddStudent] 
@StudentName NVARCHAR(255),
@DoB DATETIME,
@Parent NVARCHAR(255),
@ParentContact VARCHAR(16),
@Address NVARCHAR(255),
@Class VARCHAR(6),
AS
INSERT INTO dbo.Student
        ( StudentCode , --I set default this column
          StudentName,
          DateOfBirth
          NameParrent ,
          PhoneContact ,
          AddressParent ,
          Class ,
        )
VALUES  ( DEFAULT , --StudentCode varchar(5)
          @StudentName, --StudentName nvarchar(255)
          @DoB, --DateOfBirth datetime
          @Parent, --NameParrent nvarchar(255)
          @ParentContact, --PhoneContact varchar(16)
          @Address, --AddressParent nvarchar(255)
          @Class --Class varchar(6)
        )
-- How to return StudentCode field

Advertisement

Answer

Use OUTPUT INSERTED clause, as explained into official docs:-

INSERTED

Is a column prefix that specifies the value added by the insert or update operation. Columns prefixed with INSERTED reflect the value after the UPDATE, INSERT, or MERGE statement is completed but before triggers are executed.

so your code is going to be like this:- (is not tested, but it guides you to accurate code)

ALTER PROC [dbo].[AddStudent] 
@StudentName NVARCHAR(255),
@DoB DATETIME,
@Parent NVARCHAR(255),
@ParentContact VARCHAR(16),
@Address NVARCHAR(255),
@Class VARCHAR(6),

AS

DECLARE @StudentCodeInserted  varchar(5)

INSERT INTO dbo.Student
        ( StudentCode, --I set default this column
          StudentName,
          DateOfBirth
          NameParrent ,
          PhoneContact ,
          AddressParent ,
          Class 
        )

OUTPUT inserted.StudentCode INTO @StudentCodeInserted

VALUES  ( DEFAULT , --StudentCode varchar(5)
          @StudentName, --StudentName nvarchar(255)
          @DoB, --DateOfBirth datetime
          @Parent, --NameParrent nvarchar(255)
          @ParentContact, --PhoneContact varchar(16)
          @Address, --AddressParent nvarchar(255)
          @Class --Class varchar(6)
        )
        
Select @StudentCodeInserted as StudentCodeInserted
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement