使用JOIN将此INSERT更改为UPDATE

时间:2011-07-19 19:41:50

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

我们需要停止使用记录填充表,并且每个记录重复更新1行。没有必要保留任何历史记录。我已经使用了这个UPDATE语句但是无法获得正确的语法来考虑JOIN。

任何人都可以帮助将此INSERT INTO简单更新吗?然后,一旦我弄清楚UPDATE语句的语法,我将添加IF EXISTS(执行UPDATE)ELSE(执行插入)。我正在使用sqlfool.com的优秀脚本,但已做了一些修改,我希望这是最后一个。谢谢 !!

Insert Into [testCentral].[ReplMonitor].[dbo].[replMonitor]
(
      monitorDate
    , publicationName
    , publicationDB
    , iteration
    , tracer_id
    , distributor_latency
    , subscriber
    , subscriber_db
    , Loc_ID
    , subscriber_latency
    , overall_latency
)
Select 
      @currentDateTime
    , @publicationToTest
    , @publicationDB
    , iteration
    , tracer_id
    , IsNull(distributor_latency, 0)
    , subscriber
    , subscriber_db
    , b.LOC_ID
    , IsNull(subscriber_latency, 0)
    , IsNull(overall_latency, 
        IsNull(distributor_latency, 0) + IsNull(subscriber_latency, 0))
From @tokenResults AS a
JOIN LotteryRetail.dbo.casino b
ON 1 = 1 ;

2 个答案:

答案 0 :(得分:1)

您应该考虑使用MERGE。但这是一个包含数据的解决方案。不幸的是,我不知道你想如何加入你的桌子。所以你需要自己填写。连同应该显而易见的列。

update c
set monitorDate = @currentDateTime,
    publicationName = @publicationToTest
-- fill out the rest of your columns.
from
[testCentral].[ReplMonitor].[dbo].[replMonitor] c
join 
@tokenResults a
on --fill out your join
join 
LotteryRetail.dbo.casino b
on --fill out your join

答案 1 :(得分:0)

我同意t-clausen.dk,merge会一次性完成插入和更新。

我认为你正在为更新声明寻找这样的东西,但是如果不知道LotteryRetail.dbo.casino和@tokenResults是什么就很难说:

UPDATE [testCentral].[ReplMonitor].[dbo].[replMonitor]
SET monitorDate = @currentDateTime
    ,publicationName = @publicationToTest
    ,publicationDB = @publicationDB
    ,iteration = b.iteration
    ,tracer_id = b.tracer_id
    ,distributor_latency = b.IsNull(distributor_latency, 0)
    ,subscriber = b.subscriber
    ,subscriber_db = b.subscriber_db
    ,Loc_ID = b.b.LOC_ID
    ,subscriber_latency = b.IsNull(subscriber_latency, 0)
    ,overall_latency = b.IsNull(overall_latency, 
    IsNull(distributor_latency, 0) + IsNull(subscriber_latency, 0))
FROM LotteryRetail.dbo.casino b

这只有在[testCentral]。[ReplMonitor]。[dbo]。[replMonitor]只有一条记录时才能正常工作,否则你需要添加一个WHERE子句来限制只更改你想要更改的记录。