Suppose I have a table with columns Id
and TransactionNo
.
The Id
column has a range of ids starting from 1 to 3000.
What I need to do is to update the TransactionNo
column for the id's ranging from 1000 to 2000.
In other words, TransactionNo
must be updated only for Id
in a range of 1000 to 2000 incrementing by one (++1) for each Id
upwards.
Since it is a tedious job, I am looking for a while loop solution to update all TransactionNo
in this range of Ids.
In case there are gaps in your id
sequence and you want a continuous sequence for your generated column you could use row_number()
like shown here:
update t set trn=rn from
(select trn,row_number()
over (order by id) rn
from t1
where id>=1000 and id<=2000) t
I think you are looking for following query.
UPDATE table
SET transactionno = transactionno + 1
WHERE id >= 1000
AND id <= 2000
I think you need this:
update tablename
set transactionno = (select transactionno from tablename where id = 1000) + id - 1000
where id > 1000 and id <= 2000
it keeps the transactionno
of id = 1000
and increments the rest by 1 from id = 1001
to id = 2000
.
See the demo
Or with a CTE:
with cte as (
select transactionno from tablename where id = 1000
)
update tablename
set transactionno = (select transactionno from cte) + id - 1000
where id > 1000 and id <= 2000
See the demo
declare @startID = 1000
while(@startID <= 2000)
begin
update table set TransactionNo = value where Id = @startID;
set @StartID += 1;
end
Try This:
UPDATE TableName
SET TransactionNo = Id
WHERE Id BETWEEN 1000 AND 2000
Note: you can change this assignment statement (ie = Id
) with whatever the value you want.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.