现在的位置: 首页 > 综合 > 正文

SQL: Update from a Select

2012年11月09日 ⁄ 综合 ⁄ 共 602字 ⁄ 字号 评论关闭

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

//生成表1
CREATE TABLE [dbo].[Table_1](
 [id] [int] IDENTITY(1,1) NOT NULL,
 [name] [nchar](10)  NULL
) ON [Data Filegroup 1]

//插入两条记录到表1
INSERT [dbo].[Table_1] (name) VALUES('hello')
INSERT [dbo].[Table_1] (name) VALUES('world')
GO

 

//生成表2
CREATE TABLE [dbo].[Table_2](
 [id] [int] IDENTITY(1,1) NOT NULL,
 [name] [nchar](10)  NULL
) ON [Data Filegroup 1]

//插入两条记录到表2
INSERT [dbo].[Table_2] (name) VALUES('tom')
INSERT [dbo].[Table_2] (name) VALUES('jack')
GO

//将表2中id相同的name同步到表1中.
UPDATE [dbo].[Table_1]
SET    [dbo].[Table_1].name = [dbo].[Table_2].name

FROM   [dbo].[Table_2]
WHERE  [dbo].[Table_1].id = [dbo].[Table_2].id

GO
 

抱歉!评论已关闭.