SQL Server:如何根据where子句中的子查询更新表?

时间:2011-03-31 13:10:30

标签: sql sql-server sql-server-2008 tsql sql-update

我有一张表(包含数据),如下所示:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[lTab](
    [log_id] [int] IDENTITY(1,1) NOT NULL,
    [JobName] [nvarchar](40) NULL,
    [startTime] [datetime] NULL,
    [endTime] [datetime] NULL,
    [BatchId] [int] NULL,
    [status] [varchar](10) NULL,
    [messag] [varchar](255) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[lTab] ON
INSERT [dbo].[lTab] ([log_id], [JobName], [startTime], [endTime], [BatchId], [status], [messag]) VALUES (1, N'Job1', CAST(0x00009EB700FBF56F AS DateTime), NULL, 2, N'START', N'Test')
INSERT [dbo].[lTab] ([log_id], [JobName], [startTime], [endTime], [BatchId], [status], [messag]) VALUES (2, N'Job2', NULL, CAST(0x00009EB700FBF975 AS DateTime), 2, N'START', N'Test')
INSERT [dbo].[lTab] ([log_id], [JobName], [startTime], [endTime], [BatchId], [status], [messag]) VALUES (3, N'Job3', CAST(0x00009EB700FC287F AS DateTime), NULL, 2, N'START', N'Test')
INSERT [dbo].[lTab] ([log_id], [JobName], [startTime], [endTime], [BatchId], [status], [messag]) VALUES (4, N'Job3', NULL, CAST(0x00009EB700FC2CC6 AS DateTime), 2, N'END', N'Test')
SET IDENTITY_INSERT [dbo].[lTab] OFF

我正在尝试根据Jobname和max(log_id)更新endTime。

DECLARE @Jname VARCHAR(10)
SET @Jname = 'Job3'

UPDATE lTab
SET endTime = GETDATE() 
WHERE log_id = (SELECT JobName, MAX(log_id) AS log_id FROM dbo.lTab WHERE jobname = @Jname GROUP BY JobName)

我收到错误

sg 116, Level 16, State 1, Line 6
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

如何开展这项工作?

4 个答案:

答案 0 :(得分:3)

WITH    q AS
        (
        SELECT  *,
                ROW_NUMBER() OVER (PARTITION BY JobName ORDER BY log_id DESC) AS rn
        FROM    lTab
        WHERE   JobName = @Jname
        )
UPDATE  q
SET     endTime = GETDATE() 
WHERE   rn = 1

答案 1 :(得分:2)

从子查询中的选择列表中取出Jobname

您实际上并不需要它来获得所需的结果,SQL Server仍将返回正确的log_id。

由于您返回2个字段(JobnameMAX(Log_id))并尝试将Log_id与其匹配,因此您所拥有的内容将无效。

答案 2 :(得分:0)

此查询:

(SELECT JobName, MAX(log_id) AS log_id FROM dbo.lTab WHERE jobname = @Jname GROUP BY JobName)

返回多个结果,从查询中排除JobName。

答案 3 :(得分:0)

然而,更好的选择是

UPDATE tablename SET tablename.field1 = sourceTable.dataField
From tablename 
join sourceTable On tablename.keyfield = sourceTable.keyField
Where sourceTable.jobname = @jobName