Greg
Greg

Reputation: 47124

In a stored procedure how to run a query and conditionally do something

How would I do this in a stored procedure (SQL 2005):

count = select count(*) from table1 where line like '%success%'
if count > 0:
   delete from table1 where not line like '%success%'

Thanks for any help. My google skills are really failing me today :-(

Upvotes: 3

Views: 669

Answers (3)

danish
danish

Reputation: 5610

I would not keep the check at all. What is the purpose of that check?

Just use the delete query along with the where clause.

Upvotes: 1

Alex K.
Alex K.

Reputation: 175776

So if there are any rows where line is like success then delete any rows where line is not like success?

IF EXISTS (SELECT * from table1 where line like '%success%')
   delete from table1 where line NOT like '%success%'

Upvotes: 5

SQLMenace
SQLMenace

Reputation: 135011

I would write that this way

if exist (select 1 from table1 where line like '%success%')
begin
    delete from table1 where line not like '%success%'
end

Upvotes: 5

Related Questions