如果存在插入其他更新

时间:2012-03-02 21:08:17

标签: sql-server sql-server-2000

我在sql2000上(2008年即将推出,是的!)所以我还不能使用merge语句。

我有插入语句,但现在需要编写更新语句。我想将它包装在if exists insert else update语句中。查询更长,更复杂,但如果我能从下面的这个基本方面得到一些帮助,我想我可以得到整个事情。

insert into systemdetail 
    (systemname, projectname, systemtype)
    select  distinct T.systemname, T.projectname, S.model
        from    sysList T, requestSystems S 
        where   T.systemname = S.systemname and 
            S.systemname not in 
            (
            select d.systemname, d.ProjectName from systemdetail d,syslist t2 where t2.systemname = d.SystemName and t2.projectname=d.ProjectName
            )

用英文写出: 如果systemdetail表中存在projectname和systemname,请更新它。否则,将projectname和systemname(以及其他字段)作为新记录插入。

下面是我尝试写if if但是我被卡住了(参见查询中的???)。

if (exists (select sd.projectname, sd.systemname from systemdetail sd, sysList t where t.projectname = sd.projectname and t.systemname = sd.systemname)
    update systemDetail 
    set projectname = t.projectname, 
    systemname = t.systemname
    where ??? <-- this is where I'm stuck
else
    insert into systemdetail 
    (systemname, projectname, systemtype)
    select  distinct T.systemname, T.projectname, S.model
        from    sysList T, requestSystems S 
        where   T.systemname = S.systemname and 
            S.systemname not in 
            (
            select d.systemname, d.ProjectName from systemdetail d,syslist t2 where t2.systemname = d.SystemName and t2.projectname=d.ProjectName
            )

2 个答案:

答案 0 :(得分:2)

尝试以下方法:

-- Try update first
UPDATE
    S
SET
    systemtype = X.model
FROM
    systemDetail AS S
JOIN
(
    SELECT DISTINCT
        T.systemname, T.projectname, S.model
    FROM
        sysList T, requestSystems S 
    WHERE
        T.systemname = S.systemname
) AS X
ON
    X.systemname = S.systemname
AND X.projectname = S.projectname

IF @@ROWCOUNT = 0
BEGIN
    insert into systemdetail 
    (systemname, projectname, systemtype)
    select  distinct T.systemname, T.projectname, S.model
        from    sysList T, requestSystems S 
        where   T.systemname = S.systemname and 
            S.systemname not in 
            (
            select d.systemname, d.ProjectName from systemdetail d,syslist t2 where t2.systemname = d.SystemName and t2.projectname=d.ProjectName
            )
END

答案 1 :(得分:0)

更新语句的问题在于您要更新要搜索的两个值。您应该使用主键搜索记录,并使用该主键更新记录的其他值。您无法调用更新来更改记录的主键。