0

I am writing a sql proc with two parameters: @id and @id_group.

Consider this table group_info

ID   ID_Group    SupercededBy   Superceded   status
1    1           null           null         H
2    1           null           null         U

Given these parameters:

@id = 2 @id_group = 1

The first thing I need to do is to set the row’s SupercededBy to @id, where ID=@id and id_group=@id_group and status='H'.

Here is the statements I have written:

  update group_info
      set supercededby = @id
      where id_group=@id_group and status='H'

The second thing I need to do is to set the row’s Superceded to the id whose SupercededBy has been just updated from the above statements.

So in this example, row 2’s Superceded should be updated to 1.

But how to write the statements? I guess the statements might be something like this:

update group_info
      set superceded = **old_id**
      where id=@id

I know how to get the old_id, here it is

select id
    from group_info
    where id_group=@id_group and status='H'

But how can I use the values in the above select and insert the value to the update statements as old_id?

The final table should be

ID   ID_Group    SupercededBy   Superceded   status
1    1           2              null         H
2    1           null           1            U

I am using MS SQL Server.

2 Answers 2

3

A SELECT @variable = columnName FROM ... statement can be used like this:

DECLARE @oldId INT

select @oldId  = id
    from group_info
    where id_group=@id_group and status='H'

update group_info
      set superceded = @oldId 
      where id=@id
1
  • If the group has more ID, then the latest selected one will be used as @oldId. Nov 16, 2012 at 6:33
0

with this definition

The second thing I need to do is to 
set the row’s Superceded to the id whose SupercededBy has been 
just updated from the above statements.

it's a massoperation

update group_info
set supercededby = @id
where id_group=@id_group and status='H'


Select ID,supercededby  
into #tmp
from group_info
where id_group=@id_group and status='H'



update group_info
set superceded = #tmp.ID
from #tmp 
where group_info.ID=#tmp.supercededby

Drop table #tmp

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.