无论Update语句的标识如何,子查询都返回多个值

时间:2017-07-28 16:39:36

标签: sql sql-server

我在使用子查询返回更新语句所需的值时遇到问题。我在这里使用CRM数据库。我已经使用作业导入了一些字段,但我现在需要使用更新语句,因为导入器中并非所有字段都可用。

当我导入操作时,我使用Actionname字段作为ID字段的组合,以便在我需要对数据进行更新时为每个操作创建标识。

我需要使用特定于每个操作(2016年大会或2017年大会)的RequestorComments字段更新“主题”字段,但我的子查询未识别string, SecurityID (FK), ContactID (FK) and an identity作为唯一值的组合。

我也尝试使用select TOP 1作为子查询,但这会为每行返回“2017 Conference”。

DECLARE @Actions TABLE (ContactID nvarchar(256), PersonID int, CompletorComments nvarchar(256), RequestorComments nvarchar(256), SecurityListingID int, SubstatusCode int, CompletedDate datetime, Number int not null identity (1,1))
INSERT INTO @Actions VALUES ('34733','211','Corporation1','2017 Conference','2648','10014','2017-01-23 00:00:00')
INSERT INTO @Actions VALUES ('34733','211','Corporation2','2016 Conference','9103','10014','2016-01-23 00:00:00')

UPDATE dbo.Action
SET Subject = (select RequestorComments
           from @Actions a
           join dbo.action act (nolock)
           on act.name = 'TRST-1289' + cast(SecurityListingID as nvarchar) + ContactID + cast(Number as nvarchar)
           where  act.CreatedDate between '2017-07-27 15:00:09.540' and '2017-07-27 15:05:09.540')
,UpdatedBy = 9999
,UpdatedDate = getdate ()
--select *
from @Actions a
join dbo.action act (nolock)
on act.name = 'TRST-1289' + cast(SecurityListingID as nvarchar) + ContactID + 
cast(Number as nvarchar)
where  act.CreatedDate between '2017-07-27 15:00:09.540' and '2017-07-27 
15:05:09.540'

1 个答案:

答案 0 :(得分:1)

您不想为此使用子查询。您只想在更新语句中使用某些连接。这样的事情。

UPDATE act
SET Subject = a.RequestorComments
    , UpdatedBy = 9999
    , UpdatedDate = getdate ()
from @Actions a
join dbo.action act
on act.name = 'TRST-1289' + cast(SecurityListingID as nvarchar) + ContactID + cast(Number as nvarchar)
where  act.CreatedDate between '2017-07-27 15:00:09.540' and '2017-07-27 15:05:09.540'

你可能会注意到我删除了NOLOCK提示。这是一个不好的习惯,在任何地方抛出这个暗示,在更新中它可以真正搞砸了你。 http://blogs.sqlsentry.com/aaronbertrand/bad-habits-nolock-everywhere/

您也正在转换为varchar但未指定大小,这很重要,因为varchar的默认大小可能因使用情况而异。通过ALWAYS指定大小完全避免问题。