Guest User

Untitled

a guest
Apr 23rd, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. -- define the last customer ID handled
  2. DECLARE @LastCustomerID INT
  3. SET @LastCustomerID = 0
  4.  
  5. -- define the customer ID to be handled now
  6. DECLARE @CustomerIDToHandle INT
  7.  
  8. -- select the next customer to handle
  9. SELECT TOP 1 @CustomerIDToHandle = CustomerID
  10. FROM Sales.Customer
  11. WHERE CustomerID > @LastCustomerID
  12. ORDER BY CustomerID
  13.  
  14. -- as long as we have customers......
  15. WHILE @CustomerIDToHandle IS NOT NULL
  16. BEGIN
  17. -- call your sproc
  18.  
  19. -- set the last customer handled to the one we just handled
  20. SET @LastCustomerID = @CustomerIDToHandle
  21. SET @CustomerIDToHandle = NULL
  22.  
  23. -- select the next customer to handle
  24. SELECT TOP 1 @CustomerIDToHandle = CustomerID
  25. FROM Sales.Customer
  26. WHERE CustomerID > @LastCustomerID
  27. ORDER BY CustomerID
  28. END
  29.  
  30. -- define the last customer ID handled
  31. DECLARE @LastCustomerID INT
  32. SET @LastCustomerID = 0
  33. -- define the customer ID to be handled now
  34. DECLARE @CustomerIDToHandle INT
  35. SET @CustomerIDToHandle = 1
  36.  
  37. -- as long as we have customers......
  38. WHILE @LastCustomerID <> @CustomerIDTOHandle
  39. BEGIN
  40. SET @LastCustomerId = @CustomerIDToHandle
  41. -- select the next customer to handle
  42. SELECT TOP 1 @CustomerIDTOHandle = CustomerID
  43. FROM Sales.Customer
  44. WHERE CustomerID > @LastCustomerId
  45. ORDER BY CustomerID
  46.  
  47. IF @CustomerIDTOHandle <> @LastCustoemrID
  48. BEGIN
  49. -- call your sproc
  50. END
  51.  
  52.  
  53. END
  54.  
  55. -- Declare & init (2008 syntax)
  56. DECLARE @CustomerID INT = 0
  57.  
  58. -- Iterate over all customers
  59. WHILE (1 = 1)
  60. BEGIN
  61.  
  62. -- Get next customerId
  63. SELECT TOP 1 @CustomerID = CustomerID
  64. FROM Sales.Customer
  65. WHERE CustomerID > @CustomerId
  66. ORDER BY CustomerID
  67.  
  68. -- Exit loop if no more customers
  69. IF @@ROWCOUNT = 0 BREAK;
  70.  
  71. -- call your sproc
  72. EXEC dbo.YOURSPROC @CustomerId
  73.  
  74. END
  75.  
  76. SELECT CustomerID, CustomerSum.Total
  77.  
  78. FROM Customers
  79. CROSS APPLY ufn_ComputeCustomerTotal(Customers.CustomerID) AS CustomerSum
  80.  
  81. CREATE FUNCTION ComputeCustomerTotal
  82. (
  83. @CustomerID INT
  84. )
  85. RETURNS TABLE
  86. AS
  87. RETURN
  88. (
  89. SELECT SUM(CustomerOrder.Amount) AS Total FROM CustomerOrder WHERE CustomerID = @CustomerID
  90. )
Add Comment
Please, Sign In to add comment