?
Solved

Best way to use a procedure/function in mssql server when you have to insert and return a row

Posted on 2015-02-04
5
Medium Priority
?
62 Views
Last Modified: 2015-03-17
Hi,

I am primarily a Java developer with some level of oracle DB experience. I am having to use MSSQL server 2008 R2 for one project. I took a quick tutorial of mssql server on udemy and started creating functions and procedures.

The problem is,

a)   i need to pass a few values to a procedure or a function and insert them in a table and return.

i have read online that functions cannot be used for inserting into existing tables .. rather they only insert into temp tables.. is this true ? can you not insert into a table and return the row inserted in a function on MSSQL server? I used the below procedure anyways.

USE [KingsBayY]
GO
/****** Object:  UserDefinedFunction [dbo].[test_fn_transaction_search]    Script Date: 01/30/2015 11:57:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
					
alter PROCEDURE test_fn_transaction_insert_log @receipt varchar(25), @amount varchar(25), @stdt varchar(25), 
@enddt varchar(25)

AS

SET NOCOUNT ON

INSERT INTO [TransactionLog] ( TimeStamp, CashierID, Total,RecurringStartDate, 
RecurringStopDate, CustomerID, ReceiptNumber, Voided, Attendee, ItemLookupCode)
SELECT  CURRENT_TIMESTAMP AS [TimeStamp], tr.CashierID, @amount, @stdt,@enddt,c.ID,tr.ReceiptNumber,
tr.Voided,it.ItemLookupCode, tr.Comment
from [Transaction] tr, TransactionEntry trent, Item it, Customer c
	 where trent.TransactionID = tr.ID
	 and trent.ItemID = it.ID
	 and c.ID=tr.CustomerID
	 and tr.ReceiptNumber=@receipt
--condition to ensure no duplicates are entered	 and [TransactionLog].ID not in (select ID from [TransactionLog] where [TransactionLog].ID=tr.ID)
	 
GO

Open in new window




b)  in the above procedure, i need to return the row just inserted. how can i do this? or atleast get a return code?

c) is this even the best way of writing this procedure for the requirement? can functions be used ?
0
Comment
Question by:solarisinfosys
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
5 Comments
 
LVL 11

Expert Comment

by:HuaMinChen
ID: 40590309
Hi,
You can use SP to do insert. Here is one example.

IF ( OBJECT_ID('dbo.sp_Students_INS_byPK') IS NOT NULL ) 
   DROP PROCEDURE dbo.sp_Students_INS_byPK
GO

CREATE PROCEDURE dbo.sp_Students_INS_byPK
       @student_id                     INT                      , 
       @password                       VARCHAR(15)      = NULL  , 
       @active_flg                     TINYINT                  , 
       @lastname                       VARCHAR(30)      = NULL  , 
       @birth_dttm                     DATETIME         = NULL  , 
       @gpa                            INT              = NULL  , 
       @is_on_staff                    TINYINT                   
AS 
BEGIN 
     SET NOCOUNT ON 

     INSERT INTO dbo.Students
          ( 
            student_id                   ,
            password                     ,
            active_flg                   ,
            lastname                     ,
            birth_dttm                   ,
            gpa                          ,
            is_on_staff                  
          ) 
     VALUES 
          ( 
            @student_id                   ,
            @password                     ,
            @active_flg                   ,
            @lastname                     ,
            @birth_dttm                   ,
            @gpa                          ,
            @is_on_staff                  
          ) 

END 

GO

Open in new window

0
 

Author Comment

by:solarisinfosys
ID: 40590318
how is the above answer different from the procedure i wrote? it does not return anything.
0
 
LVL 11

Expert Comment

by:HuaMinChen
ID: 40590328
Use Output parameter like
CREATE PROCEDURE Myproc

@parm varchar(10),
**@parm1OUT varchar(30) OUTPUT**,
**@parm2OUT varchar(30) OUTPUT**
AS
  SELECT @parm1OUT='parm 1' + @parm
 SELECT @parm2OUT='parm 2' + @parm

GO

DECLARE @SQLString NVARCHAR(500)
DECLARE @ParmDefinition NVARCHAR(500)
DECLARE @parmIN VARCHAR(10)
DECLARE @parmRET1 VARCHAR(30)
DECLARE @parmRET2 VARCHAR(30)

SET @parmIN=' returned'
SET @SQLString=N'EXEC Myproc @parm,
                         @parm1OUT OUTPUT, @parm2OUT OUTPUT'
SET @ParmDefinition=N'@parm varchar(10),
                  @parm1OUT varchar(30) OUTPUT,
                  @parm2OUT varchar(30) OUTPUT'

EXECUTE sp_executesql
@SQLString,
@ParmDefinition,
@parm=@parmIN,
@parm1OUT=@parmRET1 OUTPUT,@parm2OUT=@parmRET2 OUTPUT

SELECT @parmRET1 AS "parameter 1", @parmRET2 AS "parameter 2"
GO
DROP PROCEDURE Myproc

Open in new window

0
 
LVL 66

Assisted Solution

by:Jim Horn
Jim Horn earned 750 total points
ID: 40590329
If there's an identity field that's created, and only one row is being returned, then yes you can get that value returned ...
INSERT INTO TableA (one, two, three) 
VALUES ('A', 'B', 'C') 

SELECT SCOPE_IDENTITY() as return_id_value

Open in new window


If you're inserting a set, explain in more details what you're trying to do.

Otherwise, cleaning up your code a little...
USE [KingsBayY]
GO
					
CREATE PROC test_fn_transaction_insert_log (@receipt varchar(25), @amount varchar(25), @stdt varchar(25), @enddt varchar(25)) AS

SET NOCOUNT ON

INSERT INTO [TransactionLog] ( 
   TimeStamp, CashierID, Total, RecurringStartDate, RecurringStopDate, 
   CustomerID, ReceiptNumber, Voided, Attendee, ItemLookupCode)
SELECT
   GETDATE(), tr.CashierID, @amount, @stdt, @enddt,
   c.ID, tr.ReceiptNumber, tr.Voided, it.ItemLookupCode, tr.Comment
FROM Transaction tr, 
   JOIN TransactionEntry trent ON trent.TransactionID = tr.ID  
   JOIN Item it ON trent.ItemID = it.ID
   JOIN Customer c ON c.ID=tr.CustomerID
WHERE tr.ReceiptNumber=@receipt

SELECT SCOPE_IDENTITY() as return_value 
GO

Open in new window

0
 
LVL 25

Accepted Solution

by:
DBAduck - Ben Miller earned 750 total points
ID: 40592336
You can simply use the OUTPUT clause.

Try this out, sorry if I got the tables and columns wrong (ID), but the OUTPUT clause is what you need.

DECLARE @IDs TABLE (ID int NOT NULL PRIMARY KEY)

INSERT INTO [TransactionLog] ( TimeStamp, CashierID, Total,RecurringStartDate, 
RecurringStopDate, CustomerID, ReceiptNumber, Voided, Attendee, ItemLookupCode)
OUTPUT inserted.ID INTO @IDs
SELECT  CURRENT_TIMESTAMP AS [TimeStamp], tr.CashierID, @amount, @stdt,@enddt,c.ID,tr.ReceiptNumber,
tr.Voided,it.ItemLookupCode, tr.Comment
from [Transaction] tr, TransactionEntry trent, Item it, Customer c
	 where trent.TransactionID = tr.ID
	 and trent.ItemID = it.ID
	 and c.ID=tr.CustomerID
	 and tr.ReceiptNumber=@receipt

SELECT ID,
	TimeStamp, CashierID, Total,RecurringStartDate, 
	RecurringStopDate, CustomerID, ReceiptNumber, Voided, Attendee, ItemLookupCode
FROM dbo.[Transaction] tr
INNER JOIN @IDs I ON tr.ID = I.ID

Open in new window

0

Featured Post

Get free NFR key for Veeam Availability Suite 9.5

Veeam is happy to provide a free NFR license (1 year, 2 sockets) to all certified IT Pros. The license allows for the non-production use of Veeam Availability Suite v9.5 in your home lab, without any feature limitations. It works for both VMware and Hyper-V environments

Question has a verified solution.

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

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
A Stored Procedure in Microsoft SQL Server is a powerful feature that it can be used to execute the Data Manipulation Language (DML) or Data Definition Language (DDL). Depending on business requirements, a single Stored Procedure can return differe…
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…
Suggested Courses

762 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