如何在CASE WHEN语句中包括INSERT

时间:2019-05-06 05:18:00

标签: sql sql-server

我想在iDesiredDsicount|iSubDept语句完成时将INSERT记录到表中。否则CASE WHEN将其他一些记录插入表中。

INSERT

如何在两个条件下使用SELECT CASE SELECT CASE WHEN @AmountPaid > (SELECT InvAmount from Invoice where InvNo = @InvNo) THEN INSERT INTO PaymentMemo (fld1,fld2,fld3) values(valu1,valu2,valu3) WHEN @AmountPaid = (SELECT InvAmount from Invoice where InvNo = @InvNo) THEN INSERT INTO PaymentMemo (fld1,fld2,fld3) values(valu4,valu5,valu6) END 语句。

1 个答案:

答案 0 :(得分:2)

使用它:

insert into PaymentMemo (fld1,fld2,fld3)
SELECT CASE WHEN @AmountPaid > InvAmount then valu1 WHEN @AmountPaid = InvAmount then valu4 end,  
       CASE WHEN @AmountPaid > InvAmount then valu2 WHEN @AmountPaid = InvAmount then valu5 end,
       CASE WHEN @AmountPaid > InvAmount then valu3 WHEN @AmountPaid = InvAmount then valu6 end,
from Invoice where InvNo = @InvNo

或使用动态语句,如:

declare @InsertStmnt nvarchar(max)

SELECT @InsertStmnt=  CASE
    SELECT CASE WHEN @AmountPaid > (SELECT InvAmount from Invoice where InvNo = @InvNo) THEN
    'INSERT INTO PaymentMemo (fld1,fld2,fld3) values(valu1,valu2,valu3)'
    WHEN @AmountPaid = (SELECT InvAmount from Invoice where InvNo = @InvNo) THEN
    'INSERT INTO PaymentMemo (fld1,fld2,fld3) values(valu4,valu5,valu6)'
END

exec (@InsertStmnt)

您可以动态传递valu1,valu2,valu3valu4,valu5,valu6