1

LN_REF_NO是贷款的参考编号。LN_REF_NO必须有一个 ACNO 和一个 LRAC。

它们都存储在 ACNO 列下的帐户中。

我将如何将它们分开?请看图片

ALTER PROCEDURE sp_FinalLoanPayment
AS

DECLARE @LN_REF_NO char(13)

DECLARE @TempA
    TABLE (
        [LN_REF_NO] [char](13),
        [Status] [varchar](15),
        [ACNO] [varchar](21),
        [ACNOBalance] [dbo].[Amount]
  )

DECLARE @TempL
    TABLE (
        [LN_REF_NO] [char](13),
        [Status] [varchar](15),
        [LRAC] [varchar](21),
        [LRACBalance] [dbo].[Amount]
  )
DECLARE @TempAll
    TABLE (
        [LN_REF_NO] [char](13),
        [Status] [varchar](15),
        [ACNO] [varchar](21),
        [ACNOBalance] [dbo].[Amount],
        [LRAC] [varchar](21),
        [LRACBalance] [dbo].[Amount]

  )

INSERT INTO @TempL (LN_REF_NO ,Status,LRAC,LRACBalance)
SELECT Loan.LN_REF_NO, Loan.Status,ACCOUNTS.ACNO ,ACCOUNTS.BALANCE 
FROM Loan
INNER JOIN Accounts
ON LOAN.LRAC = ACCOUNTS.ACNO  
WHERE Loan.Status ='Paid' AND ACCOUNTS.BALANCE>0 


INSERT INTO @TempA (LN_REF_NO ,Status,ACNO,ACNOBalance)
SELECT Loan.LN_REF_NO, Loan.Status,ACCOUNTS.ACNO ,ACCOUNTS.BALANCE 
FROM Loan
INNER JOIN Accounts
ON LOAN.ACNO = ACCOUNTS.ACNO  
WHERE Loan.Status ='Paid' AND ACCOUNTS.BALANCE<0  

-- START CURSOR 1
DECLARE @cursor CURSOR 
SET @cursor = CURSOR FOR
select LN_REF_NO from @TempL
OPEN @cursor

FETCH NEXT
FROM @cursor INTO 
        @LN_REF_NO

WHILE (@@FETCH_STATUS = 0)
BEGIN

INSERT INTO @TempAll (LN_REF_NO ,Status,ACNO,ACNOBalance)
select LN_REF_NO,Status,ACNO,ACNOBalance
from @TempA
where LN_REF_NO = @LN_REF_NO 

FETCH NEXT
FROM @cursor INTO 
        @LN_REF_NO

END


CLOSE @cursor
DEALLOCATE @cursor

-- CURSOR 1 END


select * from @TempAll order by LN_REF_NO

结果:

在此处输入图像描述

4

1 回答 1

1

我认为您应该能够通过以下查询获取所需的数据:

SELECT
    ln.LN_REF_NO, ln.Status, a1.ACNO, a1.BALANCE, a2.ACNO, a2.BALANCE
FROM
    dbo.Loan ln
INNER JOIN
    dbo.Accounts a1 ON ln.LRAC = a1.ACNO
INNER JOIN
    dbo.Accounts a2 ON ln.ACNO = a2.ACNO
WHERE
    ln.Status = 'Paid'
    AND a1.Balance > 0
    AND a2.Balance > 0

您基本上只需加入Accounts表两次 - 一次用于链接到Loan.LRAC,第二次用于链接Loan.ACNO

基于这两个连接,您只需从您需要的所有连接表中选择这些列 - 这就是真正的全部!没有游标,没有临时表——不需要这样的东西!

于 2013-06-07T12:57:57.933 回答