0

我有 2 个 sql 表

[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

ContractID 有 6 或 12 个分期付款,我使用 installmentNum 列通过 winform 插入我编写了这个存储过程

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

第二个用于逐一阅读所选合同的分期付款我正在尝试编写此存储过程

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

我对 spReadInstallment 的 SELECT 语句和 spInsertUpdateInstallment 的插入语句感到困惑我是初学者,无法理解背后的错误请指导我

4

1 回答 1

1

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

您的第一个存储过程正在执行upsert(更新或插入) - 它将根据为 PK 参数提供的参数插入或更新表: @ContractID@iupdate

当这两个都具有 value0时,存储的过程将执行插入。否则,它将对表执行更新。

在此处分析您是否真的需要参数的所有这些默认值。

你的第二个存储过程,毫无疑问。0在没有默认值的情况下重写它@ContractID,并且在 SELECT 操作上没有不必要的多个挂起事务:

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

SELECT    ContractID, InstallmentNumber, currentMonth, installment, commission
FROM      Installment
WHERE     ContractID = @contractid;
于 2012-05-04T16:33:54.833 回答