0

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
1
  • please do not tag your questions in the title. I have removed the SQL Server 2005 you added to your title and moved it to the tags that are at the bottom of your question. Thanks! Commented Oct 18, 2012 at 23:25

1 Answer 1

2
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
Sign up to request clarification or add additional context in comments.

8 Comments

What about the TSQL Merge Stagement
What about checking for if the record exists or not and updating if it does and inserting if it doesn't
@PreetSangha Merge is not available in SQL Server 2005
+1 - good answer despite not handling the update existing/insert new. @user204588, this gets you 90% of the way there. Shouldn't be too hard to take it the rest of the way. I'd recommend looking at Common table expressions and not in
for update, JOIN will make sure that records exist in both tables and also the name is not bad, for insert it will insert records from TableA if they do not exist in Class1, is this what are you looking for?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.