mepk
mepk

Reputation: 187

writing Insert statement in a Stored Procedure

I have 2 sql table

[dbo].[Contract]
[ContractID] pk,.....other column

[dbo].[Installment] //this table has composite primary key
[ContractID] pk n fk // it is primary and foreign key
[installmentNum] pk, // contractID and installmentnum both are the primary keys

A ContractID has 6 or 12 installments for this i used installmentNum column for insertion through a winform i write this stored procedure

ALTER PROCEDURE [dbo].[spInsertUpdateInstallment]
@ContractID int = 0,
@InstallmentNumber int = 0,
@month varchar(10),
@installment money = 0.00,
@commission money = 0.00,
@iupdate int = 0
AS
SET NOCOUNT ON 
SET XACT_ABORT ON  
BEGIN TRAN
 if @ContractID<>0 and @iupdate=0 //i'm confused here
BEGIN
INSERT INTO [dbo].[Installment] 
VALUES(@InstallmentNumber,@month,@installment,@commission)
END
if @ContractID <>0 and @month is not null and @iupdate=1
BEGIN
UPDATE [dbo].[Installment] 
SET 
[ContractID] = @ContractID,
[InstallmentNumber] = @InstallmentNumber,
[currentMonth] = @month,
[installment] = @installment,
[commission] = @commission
WHERE [ContractID] = @ContractID and [currentMonth] = @month
END
Commit

second for reading installments one by one of selected contract i'm trying to write this stored procedure

ALTER PROCEDURE [dbo].[spReadInstallment]
@ContractID int = 0
AS
SET NOCOUNT ON 
SET XACT_ABORT ON
BEGIN tran
if @ContractID<>0
begin tran
BEGIN
SELECT     ContractID, InstallmentNumber, currentMonth, installment, commission
FROM         Installment
WHERE     (ContractID = @contractid) // have doubt about the select statement?
END
commit

I have confusion About the SELECT statement of the spReadInstallment and insert statment of the spInsertUpdateInstallment I'm beginer and can't understand the mistake behind kindly guide me

Upvotes: 0

Views: 1586

Answers (1)

p.campbell
p.campbell

Reputation: 100567

if @ContractID<>0 and @iupdate=0 //i'm confused here

Your first stored procedure is performing an upsert (update or insert) - it will insert or update a table depending on the arguments given for the PK parameters: @ContractID and @iupdate

When those two both have value 0, then the stored proc will perform an insert. Otherwise, it'll perform an update to the table.

Analyse whether you really need all those default values on your parameters here.

Your second stored procedure, have no doubts. Rewrite it like this without the default value 0 on the @ContractID, and without the unnecessary multiple hanging transactions on a SELECT operation:

ALTER PROCEDURE [dbo].[spReadInstallment]
@ContractID int
AS
SET NOCOUNT ON;

SELECT    ContractID, InstallmentNumber, currentMonth, installment, commission
FROM      Installment
WHERE     ContractID = @contractid;

Upvotes: 1

Related Questions