Hi @hamed algazaly ,
Welcome to Microsoft Q&A!
SQL Server does not allow to update the identity column unlike what you could do with other columns with an update statement.
But use IDENTITY_INSERT which allows explicit values to be inserted into the identity column of a table.
SET IDENTITY_INSERT YourTable {ON|OFF}
Please refer below example:
create table yourtable
(RowName varchar(10),
ID int identity(1,1))
insert into yourtable(RowName) values
('Row1'),
('Row2'),
('Row3'),
('Row4'),
('Row5')
delete from yourtable where id=4
insert into yourtable(RowName) values
('Row6')
select * from yourtable
order by id
Output:
RowName ID
Row1 1
Row2 2
Row3 3
Row5 5
Row6 6
I want if i delete Row4
Row5 ID will update to ID 4
And Row6 update to ID 5
If you would like to achieve above, please refer below:
SET IDENTITY_INSERT yourtable ON
GO
insert into yourtable(id)
select 4
update a
set a.RowName=b.RowName
from yourtable a
left join (
select ROW_NUMBER() over (order by id) rn,rowname
from yourtable
where rowname is not null) b
on a.ID=b.rn
SET IDENTITY_INSERT yourtable OFF
select * from yourtable
order by id
Output:
RowName ID
Row1 1
Row2 2
Row3 3
Row5 4
Row6 5
NULL 6
Best regards,
Melissa
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.