0

In my stored procedure I have a temp table where I have data like below:

enter image description here

I am getting 2 rows for some employees one having emp name and other are null.

Now I need to delete the row for employee if its having duplicate rows with null emp name.

We don't need to delete if its the single row with null. I just need to delete the highlighted ones.

Please help what is the where condition here

enter image description here

1

2 Answers 2

1

You can check for name with the is null operator, and have another exists condition to check for a corresponsing id with a non-null name:

DELETE a
FROM   mytable a
WHERE  emp_name IS NULL AND
       EXISTS (SELECT *
               FROM   mytable b
               WHERE  b.emp_name IS NOT NULL AND a.emp_id = b.emp_id)
Sign up to request clarification or add additional context in comments.

4 Comments

Hi @mureinik I tried your approach but getting the error.I have edited the question and added the error.Could you please check and help
@vissubabu forgot the as, mea culpa. See my edited answer.
Hi @Mureinik though I added the as I am getting error as Msg 156, Level 15, State 1, Line 626 Incorrect syntax near the keyword 'as'..
It should be DELETE a FROM MyTable a... (though I would also use MT as the alias).
0

In SQL Server, DELETE with FROM syntax is a bit different. Try one of these:

delete @Results
from @Results r
where
    r.AffectedEndUserName is null
    and exists  (
                    select
                        1
                    from @Results rr
                    where
                        rr.AffectedEndUserName is not null and rr.EmpId = r.EmpId
                );

delete r
from @Results r
    inner join @Results rr on rr.EmpId = r.EmpId and rr.AffectedEndUserName is not null
where
    r.AffectedEndUserName is null;

I would prefer the latter; much cleaner.

Comments

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.