Reputation: 149
I want to compare @tempTable with tableA, if matched then update FieldValue of @tempTable equal to id of tableA; if not matched then insert values ,and get the id of tableA to update FieldValue of @tempTable.
The following is my SQL query:
create table [dbo].[TableA]([Id] int Indentity(1,1),[Data] [sql_variant] NULL)
declare @tempTable table (FieldValue nvarchar(1000),FieldType nvarchar(1000))
insert @tempTable values ('some content','A Type')
merge
tableA
using (
select
FieldValue
from
@tempTable
) x
on tableA.[Data] = x.FieldValue
when not matched then
insert values (x.FieldValue)
when matched then
update set x.FieldValue = tableA.[Id] ;
The following is the error message:
Unable to tie the Multi-Part ID "x.FieldValue".
The error looks like it's different data type between x.FieldValue and tableA.id, so I adjust them to the same data type, but it's still not work, and I don't know how to fix it.
Upvotes: 1
Views: 93
Reputation: 149
The following can achieve the results I want.
merge
tableA
using (
select
FieldValue
from
@tempTable
) x
on tableA.[Data] = x.FieldValue
when not matched then
insert values (x.FieldValue);
update @tempTable
set t.FieldValue = i.[Id]
from @tempTable t
join TableA i ON i.[Data] = t.FieldValue
select * from @tempTable
Upvotes: 1
Reputation: 67311
What are you trying to achieve? Your target table is tableA
, your source table is the x-aliased sub-query.
Next time please try to create a mcve. I had to modify your code slightly, but you will get the ghist:
declare @TableA TABLE([Id] int,[Data] [sql_variant] NULL)
declare @tempTable table (FieldValue nvarchar(1000),FieldType nvarchar(1000))
insert @tempTable values ('some content','A Type');
merge
@tableA a
using (
select
FieldValue
from
@tempTable
) x
on a.[Data] = x.FieldValue
when matched then
update set a.id = x.FieldValue; --fields swapped, probably not really your intention...
The point is: Your code tries to update a field of your source table. The general idea of MERGE
is
INSERT
UPDATE
DELETE
Saying this, I doubt, that the code above would need MERGE
at all...
Upvotes: 1