Solved

Stored procedure. Insert then return primary key.

Posted on 2010-08-27
15
679 Views
Last Modified: 2012-05-10
I need a quick example of writing a stored procedure that inserts a record. then returns the primary key. Please no links.

The primary key is an integer that autofills in increments.
0
Comment
Question by:techpr0
  • 4
  • 3
  • 2
  • +3
15 Comments
 
LVL 23

Expert Comment

by:Rajkumar Gs
ID: 33544536
Check this code

Raj
CREATE TABLE YourTable
(
	ID INT IDENTITY(1,1),
	NAME VARCHAR(50)
)


CREATE PROCEDURE usp_InsertRecord
(
	@name	VARCHAR(50)
	@newID	INT OUTPUT
)
AS
BEGIN
	INSERT INTO YourTable (name) VALUES (@name)

	SET @newID = SCOPE_IDENTITY()
END
GO

Open in new window

0
 
LVL 4

Accepted Solution

by:
zmorvik earned 75 total points
ID: 33544543
Write your stored procedure and then at the end put

SELECT @@IDENTITY


For example:

CREATE PROCEDURE TestProcedure
      -- Add the parameters for the stored procedure here
AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;

    -- Insert statements for procedure here
      INSERT INTO TestTable (column1, column2) VALUES ('test1', 'test2')

SELECT @@IDENTITY
END


If you are returning this to an application you are writing, you would change the SELECT @@IDENTIY to
SET @VariableName = SELECT @@IDENTITY
0
 

Author Comment

by:techpr0
ID: 33544638
I couldn't get it to work. Yes it is for an application.

I'm using this to get the returned value in the application.

Dim strCert As String = command.Parameters("RetVal").Value
ALTER PROCEDURE [dbo].[sp_AddRecord] 
	(
		@SerialNumber varchar(50)= NULL,
		@Company varchar(50)= NULL,
		@Invoice varchar(50)= NULL,
		@Inspection varchar(50)= NULL,
		@PO varchar(50) = NULL,
		@date datetime,
		@EditedBy varchar(50),
		@DateAdded datetime
	)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @RetVal As int
	DECLARE @RetID As int
	SET @RetVal = 0
	
	If Exists(Select 1 from [lxp_1z3etnasf_site_aplus_net].[dbo].[Company] WHERE [Name] = @Company)
	BEGIN
		--Get Id if it does exist
		SELECT @RetID = [ID] FROM [lxp_1z3etnasf_site_aplus_net].[dbo].[Company] WHERE [Name] = @Company
		--Insert Login and link to Company table
		INSERT INTO [lxp_1z3etnasf_site_aplus_net].[dbo].[Certifications]
           ([Serial Number]
           ,[Invoice Authorization]
           ,[Inspection Number]
           ,[PO Number]
           ,[Active]
           ,[Date]
           ,[EditedBy]
           ,[DateAdded]
           ,[CompanyID])
		 VALUES
           (@SerialNumber
           ,@Invoice
           ,@Inspection
           ,@PO
           ,'True'
           ,@Date
           ,@EditedBy
           ,@DateAdded
           ,@RetID)
           
           Set @RetVal = SCOPE_IDENTITY()
	END
	ELSE
	BEGIN
		--Insert New Company
		INSERT INTO [lxp_1z3etnasf_site_aplus_net].[dbo].[Company]
           ([Name])
		VALUES
           (@Company)
		--Get just created Company id
		SELECT @RetID = [ID] FROM [lxp_1z3etnasf_site_aplus_net].[dbo].[Company] WHERE [Name] = @Company
		--Insert Login and link to Company table
		INSERT INTO [lxp_1z3etnasf_site_aplus_net].[dbo].[Certifications]
           ([Serial Number]
           ,[Invoice Authorization]
           ,[Inspection Number]
           ,[PO Number]
           ,[Active]
           ,[Date]
           ,[EditedBy]
           ,[DateAdded]
           ,[CompanyID])
		 VALUES
           (@SerialNumber
           ,@Invoice
           ,@Inspection
           ,@PO
           ,'True'
           ,@Date
           ,@EditedBy
           ,@DateAdded
           ,@RetID)
           
           Set @RetVal = SCOPE_IDENTITY()
	END
	END

Open in new window

0
Three Reasons Why Backup is Strategic

Backup is strategic to your business because your data is strategic to your business. Without backup, your business will fail. This white paper explains why it is vital for you to design and immediately execute a backup strategy to protect 100 percent of your data.

 
LVL 23

Expert Comment

by:Rajkumar Gs
ID: 33544662
Add one output parameter to your stored procedure
@RetVal INT OUTPUT
And remove its declaration inside Stored procedure

Raj
0
 
LVL 23

Assisted Solution

by:Rajkumar Gs
Rajkumar Gs earned 50 total points
ID: 33544712
I think coding part will look like attached

Raj
Dim parameter As SqlParameter = command.Parameters.Add("@Retval", SqlDbType.Int)
parameter.Direction = ParameterDirection.Output
command.CommandText = "sp_AddRecord"
command.ExecuteNonQuery()
Dim outResult As String = parameter.Value.ToString()

Open in new window

0
 

Author Comment

by:techpr0
ID: 33547232
Changed to the following based on your previous response, but i get an error.

Incorrect Syntax near '@RetVal'
USE [lxp_1z3etnasf_site_aplus_net]
GO
/****** Object:  StoredProcedure [dbo].[sp_AddRecord]    Script Date: 08/27/2010 17:45:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



-- =============================================
-- Author:		Roy Miller
-- Create date: 12/1/2009
-- Description:	Add New Record
-- =============================================
ALTER PROCEDURE [dbo].[sp_AddRecord] 
	(
		@SerialNumber varchar(50)= NULL,
		@Company varchar(50)= NULL,
		@Invoice varchar(50)= NULL,
		@Inspection varchar(50)= NULL,
		@PO varchar(50) = NULL,
		@date datetime,
		@EditedBy varchar(50),
		@DateAdded datetime
	)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @RetID As int
	SET @RetVal = 0
	
	If Exists(Select 1 from [lxp_1z3etnasf_site_aplus_net].[dbo].[Company] WHERE [Name] = @Company)
	BEGIN
		--Get Id if it does exist
		SELECT @RetID = [ID] FROM [lxp_1z3etnasf_site_aplus_net].[dbo].[Company] WHERE [Name] = @Company
		--Insert Login and link to Company table
		INSERT INTO [lxp_1z3etnasf_site_aplus_net].[dbo].[Certifications]
           ([Serial Number]
           ,[Invoice Authorization]
           ,[Inspection Number]
           ,[PO Number]
           ,[Active]
           ,[Date]
           ,[EditedBy]
           ,[DateAdded]
           ,[CompanyID])
		 VALUES
           (@SerialNumber
           ,@Invoice
           ,@Inspection
           ,@PO
           ,'True'
           ,@Date
           ,@EditedBy
           ,@DateAdded
           ,@RetID)
           
           
	END
	ELSE
	BEGIN
		--Insert New Company
		INSERT INTO [lxp_1z3etnasf_site_aplus_net].[dbo].[Company]
           ([Name])
		VALUES
           (@Company)
		--Get just created Company id
		SELECT @RetID = [ID] FROM [lxp_1z3etnasf_site_aplus_net].[dbo].[Company] WHERE [Name] = @Company
		--Insert Login and link to Company table
		INSERT INTO [lxp_1z3etnasf_site_aplus_net].[dbo].[Certifications]
           ([Serial Number]
           ,[Invoice Authorization]
           ,[Inspection Number]
           ,[PO Number]
           ,[Active]
           ,[Date]
           ,[EditedBy]
           ,[DateAdded]
           ,[CompanyID])
		 VALUES
           (@SerialNumber
           ,@Invoice
           ,@Inspection
           ,@PO
           ,'True'
           ,@Date
           ,@EditedBy
           ,@DateAdded
           ,@RetID)
           
           
	END
	@RetVal INT OUTPUT
	END

Open in new window

0
 
LVL 22

Expert Comment

by:pivar
ID: 33550118
Hi,

How about:


USE [lxp_1z3etnasf_site_aplus_net]
GO
/****** Object:  StoredProcedure [dbo].[sp_AddRecord]    Script Date: 08/27/2010 17:45:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



-- =============================================
-- Author:              Roy Miller
-- Create date: 12/1/2009
-- Description: Add New Record
-- =============================================
ALTER PROCEDURE [dbo].[sp_AddRecord] 
        (
                @SerialNumber varchar(50)= NULL,
                @Company varchar(50)= NULL,
                @Invoice varchar(50)= NULL,
                @Inspection varchar(50)= NULL,
                @PO varchar(50) = NULL,
                @date datetime,
                @EditedBy varchar(50),
                @DateAdded datetime
        )
AS
BEGIN
        SET NOCOUNT ON;
        DECLARE @RetID As int;
        SET @RetID = 0;
        
        If Exists(Select 1 from [lxp_1z3etnasf_site_aplus_net].[dbo].[Company] WHERE [Name] = @Company)
        BEGIN
                --Get Id if it does exist
                SELECT @RetID = [ID] FROM [lxp_1z3etnasf_site_aplus_net].[dbo].[Company] WHERE [Name] = @Company
                --Insert Login and link to Company table
                INSERT INTO [lxp_1z3etnasf_site_aplus_net].[dbo].[Certifications]
           ([Serial Number]
           ,[Invoice Authorization]
           ,[Inspection Number]
           ,[PO Number]
           ,[Active]
           ,[Date]
           ,[EditedBy]
           ,[DateAdded]
           ,[CompanyID])
                 VALUES
           (@SerialNumber
           ,@Invoice
           ,@Inspection
           ,@PO
           ,'True'
           ,@Date
           ,@EditedBy
           ,@DateAdded
           ,@RetID)
           
           
        END
        ELSE
        BEGIN
                --Insert New Company
                INSERT INTO [lxp_1z3etnasf_site_aplus_net].[dbo].[Company]
           ([Name])
                VALUES
           (@Company)
                --Get just created Company id
                SELECT @RetID = [ID] FROM [lxp_1z3etnasf_site_aplus_net].[dbo].[Company] WHERE [Name] = @Company
                --Insert Login and link to Company table
                INSERT INTO [lxp_1z3etnasf_site_aplus_net].[dbo].[Certifications]
           ([Serial Number]
           ,[Invoice Authorization]
           ,[Inspection Number]
           ,[PO Number]
           ,[Active]
           ,[Date]
           ,[EditedBy]
           ,[DateAdded]
           ,[CompanyID])
                 VALUES
           (@SerialNumber
           ,@Invoice
           ,@Inspection
           ,@PO
           ,'True'
           ,@Date
           ,@EditedBy
           ,@DateAdded
           ,@RetID)
           
           
        END
        RETURN @RetID;
END

Open in new window

0
 
LVL 22

Assisted Solution

by:pivar
pivar earned 50 total points
ID: 33550241
Above would give you a return value. If you like an output parameter try this instead.
USE [lxp_1z3etnasf_site_aplus_net]
GO
/****** Object:  StoredProcedure [dbo].[sp_AddRecord]    Script Date: 08/27/2010 17:45:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



-- =============================================
-- Author:              Roy Miller
-- Create date: 12/1/2009
-- Description: Add New Record
-- =============================================
ALTER PROCEDURE [dbo].[sp_AddRecord] 
        (
                @SerialNumber varchar(50)= NULL,
                @Company varchar(50)= NULL,
                @Invoice varchar(50)= NULL,
                @Inspection varchar(50)= NULL,
                @PO varchar(50) = NULL,
                @date datetime,
                @EditedBy varchar(50),
                @DateAdded datetime,
                @RetId int OUTPUT
        )
AS
BEGIN
        SET NOCOUNT ON;
        SET @RetID = 0;
        
        If Exists(Select 1 from [lxp_1z3etnasf_site_aplus_net].[dbo].[Company] WHERE [Name] = @Company)
        BEGIN
                --Get Id if it does exist
                SELECT @RetID = [ID] FROM [lxp_1z3etnasf_site_aplus_net].[dbo].[Company] WHERE [Name] = @Company
                --Insert Login and link to Company table
                INSERT INTO [lxp_1z3etnasf_site_aplus_net].[dbo].[Certifications]
           ([Serial Number]
           ,[Invoice Authorization]
           ,[Inspection Number]
           ,[PO Number]
           ,[Active]
           ,[Date]
           ,[EditedBy]
           ,[DateAdded]
           ,[CompanyID])
                 VALUES
           (@SerialNumber
           ,@Invoice
           ,@Inspection
           ,@PO
           ,'True'
           ,@Date
           ,@EditedBy
           ,@DateAdded
           ,@RetID)
           
           
        END
        ELSE
        BEGIN
                --Insert New Company
                INSERT INTO [lxp_1z3etnasf_site_aplus_net].[dbo].[Company]
           ([Name])
                VALUES
           (@Company)
                --Get just created Company id
                SELECT @RetID = [ID] FROM [lxp_1z3etnasf_site_aplus_net].[dbo].[Company] WHERE [Name] = @Company
                --Insert Login and link to Company table
                INSERT INTO [lxp_1z3etnasf_site_aplus_net].[dbo].[Certifications]
           ([Serial Number]
           ,[Invoice Authorization]
           ,[Inspection Number]
           ,[PO Number]
           ,[Active]
           ,[Date]
           ,[EditedBy]
           ,[DateAdded]
           ,[CompanyID])
                 VALUES
           (@SerialNumber
           ,@Invoice
           ,@Inspection
           ,@PO
           ,'True'
           ,@Date
           ,@EditedBy
           ,@DateAdded
           ,@RetID)
           
           
        END
END

Open in new window

0
 
LVL 51

Expert Comment

by:Ted Bouskill
ID: 33550565
Using an IF statement in the stored procedure prevents SQL from reusing the cached execution plan which slows the server down.  I'd recommend the following:


USE [lxp_1z3etnasf_site_aplus_net]
GO
/****** Object:  StoredProcedure [dbo].[sp_AddRecord]    Script Date: 08/27/2010 17:45:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



-- =============================================
-- Author:              Roy Miller
-- Create date: 12/1/2009
-- Description: Add New Record
-- =============================================
ALTER PROCEDURE [dbo].[sp_AddRecord] 
        (
                @SerialNumber varchar(50)= NULL,
                @Company varchar(50)= NULL,
                @Invoice varchar(50)= NULL,
                @Inspection varchar(50)= NULL,
                @PO varchar(50) = NULL,
                @date datetime,
                @EditedBy varchar(50),
                @DateAdded datetime,
                @RetId int OUTPUT
        )
AS
BEGIN
        SET NOCOUNT ON;
        
        SELECT @RetID = [ID] FROM [lxp_1z3etnasf_site_aplus_net].[dbo].[Company] WHERE [Name] = @Company

        -- If @RetID IS NULL then insert one
        INSERT INTO [lxp_1z3etnasf_site_aplus_net].[dbo].[Company]
               ([Name])
           SELECT (@Company) WHERE @RetID IS NULL

        -- NOTE: Microsoft recommends using SCOPE_IDENTITY instead of @@IDENTITY
        SELECT @RetID = ISNULL(@RetID, SCOPE_IDENTITY())

        --Insert Login and link to Company table
        INSERT INTO [lxp_1z3etnasf_site_aplus_net].[dbo].[Certifications]
           ([Serial Number]
           ,[Invoice Authorization]
           ,[Inspection Number]
           ,[PO Number]
           ,[Active]
           ,[Date]
           ,[EditedBy]
           ,[DateAdded]
           ,[CompanyID])
                 VALUES
           (@SerialNumber
           ,@Invoice
           ,@Inspection
           ,@PO
           ,'True'
           ,@Date
           ,@EditedBy
           ,@DateAdded
           ,@RetID)
           
        RETURN 0
END

Open in new window

0
 

Author Comment

by:techpr0
ID: 33551075
I tried the last 3 solutions, but they give me the ID field of the Company table. I need the primary key of the Certification table (certID).

I will still be using the @RetID to link the tables.

Thanks for the help so far.
0
 

Author Comment

by:techpr0
ID: 33551310
I got it to produce the correct info. like this, but is there a better way to write it for my application or is this ok.
USE [lxp_1z3etnasf_site_aplus_net]
GO
/****** Object:  StoredProcedure [dbo].[sp_AddRecord1]    Script Date: 08/28/2010 18:09:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



-- =============================================
-- Author:              
-- Create date: 12/1/2009
-- Description: Add New Record
-- =============================================
ALTER PROCEDURE [dbo].[sp_AddRecord1] 
        (
                @SerialNumber varchar(50)= NULL,
                @Company varchar(50)= NULL,
                @Invoice varchar(50)= NULL,
                @Inspection varchar(50)= NULL,
                @PO varchar(50) = NULL,
                @date datetime,
                @EditedBy varchar(50),
                @DateAdded datetime
        )
AS
BEGIN
        SET NOCOUNT ON;
        DECLARE @RetID As int;
        SET @RetID = 0;
        
        If Exists(Select 1 from [lxp_1z3etnasf_site_aplus_net].[dbo].[Company] WHERE [Name] = @Company)
        BEGIN
                --Get Id if it does exist
                SELECT @RetID = [ID] FROM [lxp_1z3etnasf_site_aplus_net].[dbo].[Company] WHERE [Name] = @Company
                --Insert Login and link to Company table
                INSERT INTO [lxp_1z3etnasf_site_aplus_net].[dbo].[Certifications]
           ([Serial Number]
           ,[Invoice Authorization]
           ,[Inspection Number]
           ,[PO Number]
           ,[Active]
           ,[Date]
           ,[EditedBy]
           ,[DateAdded]
           ,[CompanyID])
                 VALUES
           (@SerialNumber
           ,@Invoice
           ,@Inspection
           ,@PO
           ,'True'
           ,@Date
           ,@EditedBy
           ,@DateAdded
           ,@RetID)
           
           SELECT @@identity AS newID
        END
        ELSE
        BEGIN
                --Insert New Company
                INSERT INTO [lxp_1z3etnasf_site_aplus_net].[dbo].[Company]
           ([Name])
                VALUES
           (@Company)
                --Get just created Company id
                SELECT @RetID = [ID] FROM [lxp_1z3etnasf_site_aplus_net].[dbo].[Company] WHERE [Name] = @Company
                --Insert Login and link to Company table
                INSERT INTO [lxp_1z3etnasf_site_aplus_net].[dbo].[Certifications]
           ([Serial Number]
           ,[Invoice Authorization]
           ,[Inspection Number]
           ,[PO Number]
           ,[Active]
           ,[Date]
           ,[EditedBy]
           ,[DateAdded]
           ,[CompanyID])
                 VALUES
           (@SerialNumber
           ,@Invoice
           ,@Inspection
           ,@PO
           ,'True'
           ,@Date
           ,@EditedBy
           ,@DateAdded
           ,@RetID)
           
           SELECT @@identity AS newID
        END
        
END

Open in new window

0
 
LVL 75

Expert Comment

by:Anthony Perkins
ID: 33551469
Unless you are still using SQL Server 7 do not use @@IDENTITY and instead use SCOPE_IDENTITY()
0
 
LVL 51

Assisted Solution

by:Ted Bouskill
Ted Bouskill earned 75 total points
ID: 33551629
OK, based on your last comment use this:
USE [lxp_1z3etnasf_site_aplus_net]
GO
/****** Object:  StoredProcedure [dbo].[sp_AddRecord]    Script Date: 08/27/2010 17:45:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



-- =============================================
-- Author:              Roy Miller
-- Create date: 12/1/2009
-- Description: Add New Record
-- =============================================
ALTER PROCEDURE [dbo].[sp_AddRecord] 
        (
                @SerialNumber varchar(50)= NULL,
                @Company varchar(50)= NULL,
                @Invoice varchar(50)= NULL,
                @Inspection varchar(50)= NULL,
                @PO varchar(50) = NULL,
                @date datetime,
                @EditedBy varchar(50),
                @DateAdded datetime,
                @CertId int OUTPUT
        )
AS
BEGIN
        SET NOCOUNT ON;
        
        DECLARE @companyID

        SELECT @companyID = [ID] FROM [lxp_1z3etnasf_site_aplus_net].[dbo].[Company] WHERE [Name] = @Company

        -- If @companyID IS NULL then insert one
        INSERT INTO [lxp_1z3etnasf_site_aplus_net].[dbo].[Company]
               ([Name])
           SELECT (@Company) WHERE @companyID IS NULL

        -- NOTE: Microsoft recommends using SCOPE_IDENTITY instead of @@IDENTITY
        SELECT @companyID = ISNULL(@companyID, SCOPE_IDENTITY())

        --Insert Login and link to Company table
        INSERT INTO [lxp_1z3etnasf_site_aplus_net].[dbo].[Certifications]
           ([Serial Number]
           ,[Invoice Authorization]
           ,[Inspection Number]
           ,[PO Number]
           ,[Active]
           ,[Date]
           ,[EditedBy]
           ,[DateAdded]
           ,[CompanyID])
                 VALUES
           (@SerialNumber
           ,@Invoice
           ,@Inspection
           ,@PO
           ,'True'
           ,@Date
           ,@EditedBy
           ,@DateAdded
           ,@companyID)

        SELECT @CertId = SCOPE_IDENTITY()
           
        RETURN 0
END

Open in new window

0

Featured Post

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
sql 2014,  lock limit 5 29
What is the proper way to use for criteria in left join? 7 25
Tsql query 6 19
sql server service accounts 4 19
Using SQL Scripts we can save all the SQL queries as files that we use very frequently on our database later point of time. This is one of the feature present under SQL Workshop in Oracle Application Express.
Many companies are looking to get out of the datacenter business and to services like Microsoft Azure to provide Infrastructure as a Service (IaaS) solutions for legacy client server workloads, rather than continuing to make capital investments in h…
Video by: Steve
Using examples as well as descriptions, step through each of the common simple join types, explaining differences in syntax, differences in expected outputs and showing how the queries run along with the actual outputs based upon a simple set of dem…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

813 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now