我有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的语句我是初学者,无法理解背后的错误,请指导我
答案 0 :(得分:1)
if @ContractID<>0 and @iupdate=0 //i'm confused here
您的第一个存储过程正在执行 upsert (更新或插入) - 它将根据为PK参数提供的参数插入或更新表:@ContractID
和{{1 }}
当这两个都具有值@iupdate
时,存储的proc将执行插入。否则,它将对表执行更新。
在此处分析您的参数是否确实需要所有这些默认值。
您的第二个存储过程,毫无疑问。像这样重写它而没有0
上的默认值0
,并且没有SELECT操作上不必要的多个挂起事务:
@ContractID