使用另一个表中的信息更新表中的列

Posted

技术标签:

【中文标题】使用另一个表中的信息更新表中的列【英文标题】:Update a column in table with information from another table 【发布时间】:2013-09-27 09:08:26 【问题描述】:

我已经有了这个:

USE [AdventureWorks2012];
--- somewhere create table  
IF OBJECT_ID('[dbo].[PersonPhone]','U') IS NOT NULL   
DROP TABLE [dbo].[PersonPhone]  
CREATE TABLE [dbo].[PersonPhone](  
    [BusinessEntityID] [int] NOT NULL,  
    [PhoneNumber] nvarchar(25) NOT NULL,  
    [PhoneNumberTypeID] [int] NOT NULL,  
    [ModifiedDate] [datetime] NOT NULL)  
--- and append new column  
ALTER Table [dbo].[PersonPhone]  
ADD [StartDate] date NULL  
--- after this, i want copy dates in this column (at another table, we increase dates by one)  
UPDATE [dbo].[PersonPhone]
SET [StartDate] = [NewTable].[NewDate]
FROM (
       SELECT DATEADD(day, 1, [HumanResources].[EmployeeDepartmentHistory].[StartDate]) AS [NewDate],
          row_number() over(order by (select 1)) AS [RN]
   FROM [HumanResources].[EmployeeDepartmentHistory]
 ) [NewTable]

如何改进查询以将值从 [NewTable] 复制到 [dbo].[PersonPhone].[StartDate] 行?

【问题讨论】:

【参考方案1】:

在您更新时:

UPDATE [dbo].[PersonPhone]
SET [StartDate] = DATEADD(day, 1, [HumanResources].[EmployeeDepartmentHistory].[StartDate])
FROM [HumanResources].[EmployeeDepartmentHistory]
GO

SELECT row_number() over(order by (select 1)) AS [RN] FROM [HumanResources].[EmployeeDepartmentHistory]

【讨论】:

SQL Server 告诉我“此查询返回的结果不止一个...” 现在写,“不能为日期时间调用方法” 已复制,但所有行都有一个值。如何逐行复制? 如果是这样,如果我是你,我会将更新查询放入循环语句中。

以上是关于使用另一个表中的信息更新表中的列的主要内容,如果未能解决你的问题,请参考以下文章

在对另一个表进行更新后,如何更新表中的列?

插入后使用 SQL Server 触发器更新另一个表中的列

MySQL - 更新/设置一个表中的列等于另一个表中的 MAX 值

SQL UPDATE - 如何使用另一个表更新一个表中的列?

创建一个触发器,当另一个表中的列更新时更新一个表上的列

如何优化查询以使用oracle中另一个表中的列更新表列