【问题标题】:Make tables from different databases match each other使来自不同数据库的表相互匹配
【发布时间】:2012-07-27 18:18:33
【问题描述】:

我正在尝试更新一个表,以便所有值都与不同数据库上的另一个表相同。我可以使用插入命令而不是更新命令来做到这一点。

这行得通:

INSERT [test1].[dbo].[table1]
    SELECT * FROM [source].[dbo].[table1]

这不是:

UPDATE [test2].[dbo].[table1] 
SET [source].[dbo].[table1] = [test2].[dbo].[table1]

也不是这个:

UPDATE [test2].[dbo].[table1]
SET 
     [test2].[dbo].[table1].[PKcolumn] = [source].[dbo].[table1].[PKcolumn]
    ,[test2].[dbo].[table1].[column2] = [source].[dbo].[table1].[column2] 
    ,[test2].[dbo].[table1].[column3] = [source].[dbo].[table1].[column3] 

WHERE
    [source].[dbo].[table1].[PKcolumn] = [test2].[dbo].[table1].[PKcolumn]

尽管检查了无数次错误,但结果始终是此错误消息的一些变体:

消息 4104,第 16 级,状态 1,第 1 行

无法绑定多部分标识符“source.dbo.table1.PKColumn”。

有什么建议吗?

【问题讨论】:

    标签: sql database sql-update insert-update sql-insert


    【解决方案1】:

    由于update只能影响一张表,所以不必指定:

    UPDATE dest
    SET    column2 = src.column2
    FROM   source.dbo.table1 as src
    JOIN   test2.dbo.table1 as dest
    on     dest.PKcolumn = src.PKcolumn
    

    附:根据您使用的数据库,您可能需要查看MERGE 语句。

    【讨论】:

      【解决方案2】:

      您缺少 FROM 子句(因为您在更新子句中使用了多个表) 检查这个:http://scottonwriting.net/sowblog/archive/2010/07/13/howto-update-records-in-a-database-table-with-data-from-another-table-ms-sql-server.aspx

      试试这个:

      UPDATE [test2].[dbo].[table1]
      SET 
           [test2].[dbo].[table1].[PKcolumn] = [source].[dbo].[table1].[PKcolumn]
          ,[test2].[dbo].[table1].[column2] = [source].[dbo].[table1].[column2] 
          ,[test2].[dbo].[table1].[column3] = [source].[dbo].[table1].[column3] 
      FROM [source].[dbo].[table1] JOIN [test2].[dbo].[table1]
      ON
          [source].[dbo].[table1].[PKcolumn] = [test2].[dbo].[table1].[PKcolumn]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多