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

时间:2013-09-27 09:08:27

标签: sql sql-server sql-server-2012 sql-server-express

我已经有了这个:

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 个答案:

答案 0 :(得分:2)

在您的更新:

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]