2017-07-28 77 views
1

我遇到問題,使用子查詢返回更新語句所需的值。我正在這裏使用CRM數據庫。我已經使用工作來導入一些字段,但是現在我需要使用更新語句,因爲導入器中並非所有字段都可用。子查詢返回的值超過1,無論標識爲Update語句

當我導入操作時,我使用了一個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

您能否提供操作字段的示例數據?而且,Actions和@Actions之間的連接在性能方面非常糟糕。您可能希望已將其作爲臨時表中的字段連接以便於匹配 – Eli

+0

如果'act.name'在傳遞的'act.CreatedDate'之間的'action'表中存在重複項,則會出現此錯誤 –

+0

@eli謝謝爲備註re:串聯 - 我會確保更新。插入語句下方的2個插入語句是2行樣本數據。公司1參加了2017年的評論,並需要填入「主題」字段。 Corporation2參加了2016年,並需要進入主題字段 –

回答

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的默認大小可能因使用情況而異。總是通過指定尺寸來避免這個問題。

+0

非常感謝@Sean Lange!那就是訣竅。我遇到了直接從臨時表中提取字段的問題,並決定嘗試使用基於子查詢的一些建議。我不再收到錯誤並能夠運行更新。我會確定在鑄造時指定尺寸,沒有考慮到這一點。 –

+0

非常高興這有幫助。你是否理解邏輯和爲什麼你需要這樣做而不是子查詢方法? –

+0

我相信 - 謝謝你的提問!我知道它減少了代碼量,並直接從滿足加入條件的源代碼中提取數據。在這裏使用子查詢方法的任何其他缺點(除了它不工作:))? –