使用另一个表中的信息更新表中的列
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 告诉我“此查询返回的结果不止一个...” 现在写,“不能为日期时间调用方法” 已复制,但所有行都有一个值。如何逐行复制? 如果是这样,如果我是你,我会将更新查询放入循环语句中。以上是关于使用另一个表中的信息更新表中的列的主要内容,如果未能解决你的问题,请参考以下文章
MySQL - 更新/设置一个表中的列等于另一个表中的 MAX 值