declare @all_customers as table( CustNum int );
/* --you can insert dummy data for testing purposes like so:
insert into @all_customers select 5, 1 union select 2, 1 --*/
while (0 < (select count(*) from @all_customers))
begin
declare @current_customer int = (select top 1 CustNum from @all_customers);
declare @balance money = (select acct_balance from [crrsql].[dbo].[Customer] where CustNum = @current_customer);
update [crrsql].[dbo].[Customer] set Acct_balance = 0;
INSERT INTO [crrsql].[dbo].[AR_Transactions] (cashier_ID, CustNum, Balance) VALUES (100199, user, abs(@balance));
delete @all_customers where customernumber = @current_customer;
end
Do i need to change the word table to the actual table name…or is that a keyword and if so how do i specify the table Customers
Basically i need to loop through [dbo].[Customer] table
This is creating a table variable called
@all_customers. Your code then goes on to iterate through this by taking the ID from top row from this temporary table, processing the customer with that ID, then removing the process ID from your list and repeating until the table is empty (i.e. all IDs have been processed). You can’t change the wordtablehere, no. (This is essentially the same as using a cursor on the customers table I supposed but allowing you to modify the table underneath – I guess it isn’t quite as efficient, though.)If you want to process all you customers in this loop then you probably want to load their IDs into this table, e.g.
That all said, I don’t see why you need the loop here. You could probably also just do:
to process all records in one go. (If you wanted to select a subset of customers you could do that with where clauses here too.)
However this may not be appropriate if you have triggers on those tables that fire after each row update – there may be a deliberate reason they’re processed one at a time. If there’s no triggers, though, I can’t see a reason not to do the whole update at once. If it was intended as safety then as long as you wrap the whole thing in a transaction it doesn’t matter which way you do it – they’re equally as safe.