Search code examples
sql-serversql-server-2000

if exists insert else update


I'm on an sql2000 (2008 coming soon, yay!) so I can't use the merge statement yet.

I have the insert statment but now need to compose the update statement. I'd like to wrap this in an if exists insert else update statement. The query is longer and more complex but if I can get some help with this basic one below, I think I can get the whole thing.

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
            )

Written out in English: If the projectname and systemname exists in the systemdetail table, update it. Otherwise, insert the projectname and systemname (and other fields) as a new record.

Below is my attempt at writing the if exists but I'm stuck (see ??? within the query).

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
            )

Solution

  • Try the following:

    -- 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