用内连接替换游标

问题描述 投票:0回答:0

enter image description here我正在尝试用内部连接替换下面的查询,而不使用像 while 这样的任何循环。请对此有任何建议,

DECLARE @receipt_id int 
DECLARE @receipt_nbr varchar(max)

DECLARE Receipt_Cursor CURSOR FOR 
    SELECT receipt_id 
    FROM receipt 
    WHERE Receipt_ID <> 0 
      AND Cash_Receipt_Nbr <> '0' 
    ORDER BY 1 DESC

OPEN Cash_Receipt_Cursor

FETCH NEXT FROM Cash_Receipt_Cursor INTO @cash_receipt_id

WHILE @@FETCH_STATUS = 0  
BEGIN  
    --Logic
    SET receipt_nbr = (SELECT receipt_nbr FROM receipt 
                       WHERE receipt_id = @receipt_id)

    UPDATE receipt 
    SET original_receipt = @receipt_id 
    WHERE receipt_nbr LIKE @receipt_nbr+'%'

    PRINT @receipt_nbr

    FETCH NEXT FROM Receipt_Cursor INTO @receipt_id
END 

CLOSE Receipt_Cursor  
DEALLOCATE Receipt_Cursor    

我们必须根据收据编号计算原始收据并更新它。在对现有收据进行任何修改时,将在表格中插入新的插入内容,收据编号为旧收据编号+字符,我们可以从中识别原始收据并更新它

enter image description here

sql sql-server join cursor inner-join
© www.soinside.com 2019 - 2024. All rights reserved.