我正在努力弄清楚如何使用If/Then/Else方案進行更新。遊標正在抓取select語句中的記錄,然後將它們與鏈接服務器中的不同表進行比較。然後,如果它找到匹配的記錄,請更新光標的計數。如果它找不到匹配的記錄,則將該行插入表中。使用If/Then/Else更新遊標SQL語句
遊標在下方,我當前的更新命令僅用於更新記錄找到匹配項的計數。
DECLARE @cono INT
DECLARE @repno NVARCHAR(10)
DECLARE @date DATETIME
DECLARE @count INT
DECLARE cur CURSOR FOR
SELECT '1' AS PPCONO,
b.new_SalesrepId AS PPREP1,
MAX(CONVERT(VARCHAR(8), (d.ScheduledStart - c.TimeZoneBias/CAST(24 * 60 AS FLOAT)), 112)) AS PPDATE,
COUNT(b.new_SalesrepId) AS PPCOUNT,
MAX(CONVERT(VARCHAR(8), (a.ActualEnd - c.TimeZoneBias/CAST(24 * 60 AS FLOAT)), 112)) AS ClosedOn
FROM ActivityPointerBase AS a
join SystemUserExtensionBase AS b ON b.SystemUserId = a.OwnerId
join UserSettingsBase AS c ON c.SystemUserId = b.SystemUserId
join ActivityPartyBase AS d ON d.ActivityId = a.ActivityId
WHERE b.new_SalesrepId <> '99999999'
and a.ActivityTypeCode = '4201'
and b.new_SalesrepId is not NULL
and a.StateCode = '1'
and d.ParticipationTypeMask = '9'
and CONVERT(varchar(8), a.ActualEnd - c.TimeZoneBias/cast(24 * 60 as float), 112) >= dateadd(day,datediff(day,1,CONVERT(varchar(8), GetDate(), 112)),0)
and CONVERT(varchar(8), a.ActualEnd - c.TimeZoneBias/cast(24 * 60 as float), 112) < dateadd(day,datediff(day,0,CONVERT(varchar(8), GetDate(), 112)),0)
/* and CONVERT(VARCHAR(8), a.ActualEnd - c.TimeZoneBias/CAST(24 * 60 AS FLOAT), 112) < CONVERT(VARCHAR(8), GETDATE(), 112) */
group by b.new_SalesrepId,
CONVERT(varchar(8), (d.ScheduledStart - c.TimeZoneBias/cast(24 * 60 as float)), 112)
order by b.new_SalesrepId ASC;
FETCH NEXT FROM cur INTO @cono, @repno, @date, @count
WHILE (@@FETCH_STATUS=0)
BEGIN
UPDATE [AS400].S062f7ar.APLUS83MDS.PEPAPPTS01
SET PPCOUNT = PPCOUNT + @count
WHERE PPCONO = @cono
and PPREP1 = @repno
and PPDATE = @date
FETCH NEXT FROM cur INTO @cono, @repno, @date, @count
END
CLOSE cur
DEALLOCATE cur
不知道如何完成SQL中的IF/Then/Else場景。我做了一點研究,也許使用Case是要走的路,但是你可以使用Update命令來做到這一點嗎?我在SQL 2008上。
這是一個動態CRM數據庫? – Donal 2014-10-05 18:14:43
是的。 MSCRM 2011 – 2014-10-05 18:16:01
什麼是主鍵列在 – 2014-10-05 18:19:51