Question : TSQL for Insert

Hello All,

I have to write a insert statement to insert the records from existing table with different TranID

Can anyone help me with the SQL statement.

Thanks,
-B
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
TranMaster
TrainID  ID   
80       1    
81       1    
82       1
92       4
93       4
94       4

TranDetails
TranDetails TrainID  ID   Remarks
1           80       1    aaa 
2           81       1    bbb
3           82       1    ccc

I need to add
4           92       4    aaa
5           93       4    bbb
6           94       4    ccc

These records need to be added in the Trandetails table where ID = 1 for ID = 4 but with the corrosponding TrainID from TranMaster (ID = 4)

Answer : TSQL for Insert

Ok...

It took a while but here is your solution. It is working however the mechanics of it may not be that obvious. You have to use MERGE statement to capture the newly generated keys from TranMaster table together with remarks which where not inserted.

I think it could be worth to write and article explaining how and why it works so please have a look at the code and if you need me to explain any part of it now, just let me know.

Oh, and if you could give me some more background it may help me with the article. How did you come to such problem, why are you copying the rows? Could you give more real life story to the query?
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
declare @newValues table (TrainId int, Id int, Remarks varchar(32))

merge TranMaster as target
using (
	select 
		 TrainId
		,4
		,Remarks 
	from TranDetails
	) as source(TrainId, Id, Remarks)
On (0=1)
WHEN NOT MATCHED THEN
	insert (Id)
	values (source.Id)
	output inserted.TrainId, source.Id, source.Remarks
	into @newValues;
	
insert into TranDetails 
select * from @newValues
Random Solutions  
 
programming4us programming4us