2

I have thousands of rows in a sql server table which have a START row, I need to update the table and INSERT an END row for each of them.

 select  distinct transaction_id from transactions t1
      where
        this_status_id = 2 and that_type_id = 1
              and not exists
              (
              select  *
              from    transactions t2
              where   t2.transaction_id = t1.transaction_id
                      and t2.this_status_id in (1,3,4)
                      and t2.that_type_id = 1
              )

This select returns a list of IDs (not the primary key) I need to loop through each of the ids from the above select, and INSERT into the same table like:

INSERT INTO transactions VALUES (@transaction_id, "finished", 1, 2, GETDATE())
2
  • 2
    Why reinsert the same ID's? Why don't you perform an UPDATE? Commented May 23, 2017 at 15:49
  • 4
    Why Loop? INSERT into transactions SELECT distinct transaction_ID, 'finished',1,2,getdate() FROM transactions from MSFT (Insert into select...syntax. Loops are slow... set based processing in a RDBMS is so much more efficient. Commented May 23, 2017 at 15:49

1 Answer 1

3

Why loop when you could just:

insert into transactions
select distinct transaction_id, 'finished', 1, 2, getdate()
from transactions
where this_status_id = 2 
  and that_type_id = 1
  and not exists (
    select  1
    from  transactions t2
    where t2.transaction_id = t1.transaction_id
      and t2.this_status_id in (1,3,4)
      and t2.that_type_id = 1
  );

Using a temporary table:

select distinct transaction_id 
into #TempTable
from transactions t1
where this_status_id = 2 
  and that_type_id = 1
  and not exists (
    select  1
    from  transactions t2
    where t2.transaction_id = t1.transaction_id
      and t2.this_status_id in (1,3,4)
      and t2.that_type_id = 1
  );

insert into transactions
distinct transaction_id, 'finished', 1, 2, getdate()
from #TempTable;
Sign up to request clarification or add additional context in comments.

2 Comments

my select distinct is a crazy long select with not exists etc does that matter since it just brings back a long list of IDs>? I've update my question to show the large SELECT to get the ids
@user3437721 It shouldn't. If you want to dump it into a temporary table first that would be fine as well.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.