我在sql server表中有数千行,其中有START
行,我需要更新表格,INSERT
每行END
行。
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
)
此选择返回ID列表(不是主键) 我需要从上面的select中循环遍历每个id,然后INSERT到同一个表中,如:
INSERT INTO transactions VALUES (@transaction_id, "finished", 1, 2, GETDATE())
答案 0 :(得分:3)
为什么在你可以的时候循环:
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
);
使用临时表:
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;