Avatar of Queennie L
Queennie L

asked on 

Update a column based on the value on another column

I have an SQL table dbo.aTest. I want to update Col3Update if Col1 is AA and whatever value in Col2, copy that value in Col3Update from Col1 - values AA,BB,CC,DD,EE and next Col1 that starts with AA again. See attached.

I have a Cursor here that was answered by Ryan Chong. Thank you again Ryan Chong.

declare @uniqueid int;
declare @column2 nvarchar(100);
declare @last_column2 nvarchar(100);
declare @cnt int;

declare cur cursor for  
select uniqueid, [col2]
from dbo.aTest
where  [col1] = 'AA'  
order by uniqueid

open cur  
fetch next from cur into @uniqueid, @column2

set @last_column2 = ''
set @cnt = 0

while @@fetch_status = 0  
begin  
       if @last_column2 = '' or (len(@column2)> 1 and @cnt > 1)
			set @last_column2 = @column2
			
	   update a 
	   set Col3Update = @last_column2 
	   from dbo.aTest a
	   where uniqueid = @uniqueid
	   set @cnt = @cnt + 1
	   
       fetch next from cur into @uniqueid, @column2  
end 

close cur;
deallocate cur;

select * from dbo.aTest
order by uniqueid

Open in new window


What I did  wrong in this cursor?

Please help.

Thank you again for all your help.
SQL_and_OUTPUT_NUMBERS.xlsx
Microsoft SQL ServerSQL

Avatar of undefined
Last Comment
Queennie L

8/22/2022 - Mon