【问题标题】:How can I fix the error : Multi-Part ID when update a field of @tempTable如何修复错误:更新@tempTable 的字段时的多部分 ID
【发布时间】:2019-07-06 18:24:26
【问题描述】:

我想比较@tempTable 和tableA,如果匹配则更新@tempTable 的FieldValue 等于tableA 的id;如果不匹配则插入值,并获取tableA的id来更新@tempTable的FieldValue。

以下是我的 SQL 查询:

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] ;

以下是错误信息:

无法绑定多部分 ID“x.FieldValue”。

这个错误看起来是x.FieldValue和tableA.id的数据类型不同,所以我把它们调整为相同的数据类型,但还是不行,不知道怎么解决。

【问题讨论】:

  • 添加到 Schnugo 的响应中 - 您要更新的表是 tableA。您无法更新 x(即 @tempTable)中的列。
  • 谢谢,我解决了我的问题并分开了写作。

标签: sql-server tsql sql-server-2008 merge sql-merge


【解决方案1】:

以下可以达到我想要的效果。

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

【讨论】:

    【解决方案2】:

    你想达到什么目的?您的目标表是tableA,您的源表是 x 别名子查询

    下次请尝试创建mcve。我不得不稍微修改你的代码,但你会明白的:

    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...
    

    重点是:您的代码尝试更新您的 source 表的字段。 MERGE的大致思路是

    • 我们以一张表为目标,希望在其中插入/更新/删除一些记录。
    • 我们使用第二组数据来比较并用于这些操作
    • 我们发现在源中在目标中缺少的行 -> INSERT
    • 我们发现行在源中存在于目标中 -> UPDATE
    • 我们发现在目标中在源中缺少的行 -> DELETE

    这么说,我怀疑上面的代码是否需要MERGE...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-21
      • 2021-07-18
      相关资源
      最近更新 更多