To tylko szybkie demo. Możesz użyć nowego identyfikatora do wstawienia w celu aktualizacji, wstawienia do innej tabeli, zapytania itp. W inny sposób. Mając nadzieję, że nie wkładać błędy w skrypcie podczas formatowania, edycja po
-- run [1] before this script once to have environment
--create temporary table once if not dropped after
-- really only ID field is needed, the others are for illustration
create table #temp_id (Id int, d1 int, d2 int)
select * from Table2;-- this is read-only, filled once here source
select * from Table1;--interesting for following runs
insert into Table1
OUTPUT INSERTED.id
-- really only ID is needed, the rest is for illustration
, inserted.d1, inserted.d2 INTO #temp_id
select field1, field2, null-- null to be merged later
-- or inserted/updated into another table
from Table2;
select * from Table1;
select * from #temp_id;
MERGE Table1 AS TARGET
USING #temp_id AS SOURCE
ON (TARGET.id = SOURCE.id)
WHEN MATCHED
--AND OR are redundant if Table1.ID is PK
THEN
UPDATE SET TARGET.IDnew = SOURCE.id;
select * from Table1;
--drop table #temp_id
--drop table table1
--drop table table2
[1]
odtwarzając tabele z pytaniem i wypełnienie danych
create table Table1(Id int identity primary key, d1 int, d2 int, IDnew int)
create table Table2(field1 int, field2 int)
insert into table2 values(111,222)
insert into table2 values(333,444)
Nigdy w żadnym wypadku nie używaj id_current do tego, NIE zwróci poprawnego wyniku, jeśli masz wielu użytkowników! Wynik jest najlepszym wyborem lub scope_identity(), jeśli twoja wersja nie obsługuje klauzuli wyjścia. – HLGEM