troubleshooting Question

Update a column based on the value on another column

Avatar of Queennie L
Queennie L asked on
Microsoft SQL ServerSQL
5 Comments1 Solution92 ViewsLast Modified:
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

What I did  wrong in this cursor?

Please help.

Thank you again for all your help.
SQL_and_OUTPUT_NUMBERS.xlsx
ASKER CERTIFIED SOLUTION
Join our community to see this answer!
Unlock 1 Answer and 5 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 5 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros