0

I have a pretty much simple and self explanatory SQL statement:

ALTER PROCEDURE [dbo].[sp_getAllDebatesForAlias](@SubjectAlias nchar(30))
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT *
    FROM tblDebates
    WHERE (SubjectID1 in (SELECT SubjectID FROM tblSubjectAlias WHERE SubjectAlias = @SubjectAlias)) 
        OR (SubjectID2 in (SELECT SubjectID FROM tblSubjectAlias WHERE SubjectAlias = @SubjectAlias)) ;
END

I am certain that there is a way to make this statement more efficient, at least get rid of that multiple creation of the same table in the in section, i.e., the

SELECT SubjectID FROM tblSubjectAlias WHERE SubjectAlias = @SubjectAlias

part.

Any ideas?

2 Answers 2

1

Try:

select d.* from tblDebates d
where exists
(select 1
 from tblSubjectAlias s
 where s.SubjectID in (d.SubjectID1, d.SubjectID2) and
       s.SubjectAlias = @SubjectAlias)
Sign up to request clarification or add additional context in comments.

Comments

1
SELECT d.*
FROM tblDebates d
inner join tblSubjectAlias s on s.SubjectID in (d.SubjectID1, d.SubjectID2)
where s.SubjectAlias = @SubjectAlias

2 Comments

Not quite the same; if there are multiple subjects with the same alias, each Debate record may be returned multiple times (once for each matching subject).
You are right. A select distinct ... might be suitable for the OPs needs.

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.