Hi,For the past two days, I was trying to manipulate the results from test table to test_temp table using the fetch and cursor but can't get the results and hit a lot of errors. Please find the tables and my sql below. The rule here is; if there is a NULL value in subgroup column for SMEAST unit and BASE data_view, it will add additional two more rows and append SWHGRP and SMASGRP in subgroup.test tableorganization data_view subgroup amountEAGLE INTERCO SMASGRP 10EAGLE OWNER SWHGRP 15SMEAST BASE NULL 5SMEAST OWNER SWHGRP 18
test_temp tableorganization data_view subgroup amountEAGLE INTERCO SMASGRP 10EAGLE OWNER SWHGRP 15SMEAST BASE NULL 5SMEAST BASE SWHGRP 10SMEAST BASE SMASGRP 5SMEAST OWNER SWHGRP 18
The sql code:declare @organization varchar(16), @data_view varchar(16),@subgroup varchar(16),@i intset @i=0DECLARE org_cursor CURSOR FORselect organization, data_view, subgroup from testopen org_cursorfetch next from org_cursor into @organization, @data_view, @subgroupwhile @@fetch_status = 0beginset @i=@i+1if @i=1 beginexec('drop table test_tempif @organization = ''SMEAST'' and @data_view = ''BASE'' and @subgroup is NULLbeginSELECT organization, data_view, ''SWHGRP'' as subgroup, amount*2 as amountinto test_tempFROM testinsert into test_tempSELECT organization, data_view, ''SMASGRP'' as subgroup, amountFROM testendelsebeginSELECT organization, data_view, subgroup, amountinto test_tempFROM testend')endelsebeginif @i>1 exec('if @organization = ''SMEAST'' and @data_view = ''BASE'' and @subgroup is NULLbegininsert into test_tempSELECT organization, data_view, ''SWHGRP'' as subgroup, amount*2 as amountFROM testinsert into test_tempSELECT organization, data_view, ''SMASGRP'' as subgroup, amountFROM testendelsebegininsert into test_tempSELECT organization, data_view, subgroup, amountFROM testend')endfetch next from org_cursorinto @organization, @data_view, @subgroupendclose org_cursordeallocate org_cursorselect * from test_tempI am not sure if my objective can be achieved by using fetch and cursor method. Hope someone here can enlighten me. Thanks!