0

我正在尝试将 if else 从另一个表(表类型)插入到一个表中。

我遇到的问题基本上是脚本第一次运行时会将所有数据添加到表中,但是如果之后将某些内容添加到源数据中,它不会添加新记录,我不知道为什么。

我不能包含确切的代码,但它看起来像这样......

UPDATE CUSTOMER
Set Target.Desc = Source.Desc
From @source source
WHERE Target.AccountNumber = Source.AccountNumber

IF @@ROWCOUNT=0
   INSERT INTO CUSTOMER(AccountNumber, Desc)
      SELECT Source.AccountNumber, Source.Desc
      FROM @Source Source

我也尝试过传统的 if else 插入,但结果相同。

您能看到任何可能阻止插入新添加的记录的错误吗?

4

5 回答 5

2

您当前的代码只有在@source包含所有现有行或所有新行时才能正常工作。

MERGE如果不是这种情况,您可以使用

MERGE CUSTOMER AS target
USING @source AS source
ON ( target.AccountNumber = source.AccountNumber )
WHEN MATCHED THEN
  UPDATE SET [Desc] = source.[Desc]
WHEN NOT MATCHED THEN
  INSERT (AccountNumber, [Desc])
  VALUES (AccountNumber, [Desc]); 
于 2013-11-13T10:12:33.380 回答
0
-- update all existing rows
update c set 
    c.Desc = s.Desc
from CUSTOMER c
join @source s on s.AccountNumber=c.AccountNumber

-- insert all missing rows
insert into CUSTOMER (AccountNumber, Desc)
select s.AccountNumber, s.Desc
from @Source s
where not exists(
    select *
    from CUSTOMER c
    where c.AccountNumber=s.AccountNumber
)
于 2013-11-13T10:13:30.440 回答
0

The first time, there is no data in your target so @@rowcount is 0. Next time, the update updates all data and @@rowcount is not 0 and you get no data inserted. You should not use @@rowcount but do what Andrew suggest: do both UPDATE and INSERT or MERGE (do both in one statement)

于 2013-11-13T10:14:36.950 回答
0

这样做而不是使用@@ROWCOUNT 怎么样

-- update existing customers
UPDATE c
SET c.Desc = Source.Desc
FROM @source source
INNER JOIN CUSTOMER c ON c.AccountNumber = Source.AccountNumber

-- insert new customers
INSERT INTO CUSTOMER(AccountNumber, Desc)
SELECT Source.AccountNumber, Source.Desc
FROM @Source Source
LEFT JOIN CUSTOMER c ON Source.AccountNumber = c.AccountNumber
WHERE c.AccountNumber IS NULL
于 2013-11-13T09:59:45.203 回答
0

@@ROWCOUNT 值包含受影响的行数。只有当所有记录都是新的时,插入语句才有效。并且它不会进行更新。如果任何记录得到更新,即使源包含新记录,它也不会插入

如果您的要求是更新现有记录并从源插入新记录,您可以使用以下代码。

-- update existing Rows
UPDATE CUSTOMER 
SET CUSTOMER.Desc = SOURCE.Desc
from @SOURCE Source
WHERE Source.AccountNumber=CUSTOMER.AccountNumber

-- Insert New Data
INSERT INTO CUSTOMER (AccountNumber, Desc)
SELECT s.AccountNumber, s.Desc
FROM @Source Source
WHERE not exists( SELECT 1
                  FROM CUSTOMER 
                  WHERE CUSTOMER.AccountNumber=Source.AccountNumber)
于 2013-11-13T10:07:03.733 回答