Search code examples
sql-servert-sqlsql-server-2005declarative

How can I do this without a cursor or loop?


I hear to use Declarative programming but I have no idea how to do something like this in sql server 2005 (I typed this up really fast so I'm not sure if all the syntax is correct but I think you'll understand what I'm looking for)

declare curs cursor for
select @Name, @Description, @Id FROM TableA
open curs
while(1=1) 
begin
    fetch next from curs into
        @Name,
        @Description,
        @Id
    if(@@fetch_status<>0) break

    set @recordCount = (SELECT COUNT(*) As RecordCount FROM Class1 WHERE          
            Class1Id = @Id)
    if(@recordCount > 0)
    begin

        if(@Name = 'BAD NAME') CONTINUE
        UPDATE Class1 SET 
            Name = @Name
            , Description = @Description
            WHERE Class1Id = @Id
    end
    else
    begin
        INSERT INTO Class1 (Class1Id, Name, Description)
        VALUES (@Id, @Name, @Description)
    end

end
close curs
deallocate curs

Solution

  • UPDATE Class1 
    SET Name = t.Name, 
    Description = t.Description
    FROM Class1 c 
    JOIN TableA t ON c.id=t.id
    WHERE t.name <> 'BAD NAME'
    
    INSERT INTO Class1 (Class1Id, Name, Description)
    select t.Id, t.Name, t.Description
    FROM TableA t
    LEFT JOIN Class1  c on t.id=c.id
    where c.id IS NULL