Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 If not exist insert else update

Author  Topic 

Vack
Aged Yak Warrior

530 Posts

Posted - 2014-02-17 : 14:30:49
How do I Use the insert code below only if a record does not exist in the cisect table? Then if it exists I just want to

update cisect
set ml_desc_0 = cus_type_desc
from artypfil_sql A join cisect c on a.cus_type_cd = c.sct_code



INSERT INTO [002].[dbo].[cisect]
([sct_code]
,[ml_desc_0]
,[syscreated]
,[syscreator]
,[sysmodified]
,[sysmodifier]
)
select
cus_type_cd,
cus_type_desc,
GETDATE(),
0,
GETDATE(),
0
from artypfil_sql

Vack
Aged Yak Warrior

530 Posts

Posted - 2014-02-17 : 14:36:40
I seem to have stumbled across an answer. This seems to work.
update cisect
set ml_desc_0 = cus_type_desc
from artypfil_sql A join cisect c on a.cus_type_cd = c.sct_code
if @@ROWCOUNT =0


INSERT INTO [002].[dbo].[cisect]
([sct_code]
,[ml_desc_0]
,[syscreated]
,[syscreator]
,[sysmodified]
,[sysmodifier]
)
select
cus_type_cd,
cus_type_desc,
GETDATE(),
0,
GETDATE(),
0
from artypfil_sql
GO







Go to Top of Page

Vack
Aged Yak Warrior

530 Posts

Posted - 2014-02-17 : 14:38:15
Actually I take that back. It won't insert a new row. Only updates.
Go to Top of Page

Vack
Aged Yak Warrior

530 Posts

Posted - 2014-02-17 : 15:03:48
This works perfect

merge into cisect c
using (select cus_type_cd, cus_type_desc from artypfil_sql) a
on (c.sct_code = a.cus_type_cd)
when matched then
update set c.ml_desc_0 = a.cus_type_desc
when not matched then

INSERT
([sct_code]
,[ml_desc_0]
,[syscreated]
,[syscreator]
,[sysmodified]
,[sysmodifier]
)
values(
cus_type_cd,
cus_type_desc,
GETDATE(),
0,
GETDATE(),
0
)
when not matched by source
then delete;
Go to Top of Page
   

- Advertisement -