2
DECLARE @PaymentTime VARCHAR (50)

DECLARE @DueDate VARCHAR (50)
DECLARE @CustomerID int

DECLARE MYCURSOR5 CURSOR 
FOR SELECT   distinct  Payment.PaymentTime,Invoice.DueDate, Customer.CustomerID
FROM         Cus_Cred_Terms INNER JOIN
                      Customer ON Cus_Cred_Terms.CustomerID = Customer.CustomerID INNER JOIN
                      Payment ON Customer.CustomerID = Payment.CustomerID INNER JOIN
                      Invoice ON Payment.InvoiceID = Invoice.InvoiceID


open MYCURSOR5 

FETCH MYCURSOR5 INTO @PaymentTime, @DueDate, @CustomerID

WHILE @@FETCH_STATUS = 0
BEGIN 


if(@PaymentTime > @DueDate)
begin
print'payment time:'
PRINT @PaymentTime 
print'due date:'
PRINT @DueDate 

print''
print @CustomerID
print''
update dbo.Cus_Cred_Terms
set dbo.Cus_Cred_Terms.CreditAllowed = 0
FROM Cus_Cred_Terms INNER JOIN
 Customer ON Cus_Cred_Terms.CustomerID = Customer.CustomerID INNER JOIN
 Payment ON Customer.CustomerID = Payment.CustomerID
 where Customer.CustomerID = @CustomerID and dbo.Cus_Cred_Terms.CreditAllowed = 1
end



FETCH MYCURSOR5  INTO @PaymentTime, @DueDate, @CustomerID

END
CLOSE MYCURSOR5

它遍历每个字段,检查 DueDate 是否小于实际 PaymentDate,如果小于,则将另一个表中的字段设置为 0(1 表示允许信用,0 表示不允许信用)

所以问题是,我可以避免使用光标来执行此操作吗?如果您需要更多信息,请询问。

4

1 回答 1

1

尝试这样的事情:

;WITH CTE AS 
(
    SELECT DISTINCT  
        Customer.CustomerID
    FROM         
        Cus_Cred_Terms 
    INNER JOIN
        Customer ON Cus_Cred_Terms.CustomerID = Customer.CustomerID 
    INNER JOIN
        Payment ON Customer.CustomerID = Payment.CustomerID 
    INNER JOIN
        Invoice ON Payment.InvoiceID = Invoice.InvoiceID
    WHERE
        Payment.PaymentTime > Invoice.DueDate
)
UPDATE
    dbo.Cus_Cred_Terms
SET
    dbo.Cus_Cred_Terms.CreditAllowed = 0
FROM 
    CTE 
WHERE 
    dbo.Cus_Cred_Terms.CustomerID = CTE.CustomerID
    AND dbo.Cus_Cred_Terms.CreditAllowed = 1

CTE(通用表表达式)基本上具有SELECT您的光标所具有的 - 除了它还检查约束Payment.PaymentTime > Invoice.DueDate。仅选择与此条件匹配的那些客户 ID。

如果该表中的列等于 1 ,则根据这些CustomerIDdbo.Cus_Cred_Terms更新该表。CreditAllowedCustomerID

于 2012-11-22T16:39:40.390 回答