Smart questions
Smart answers
Smart people
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Member Login

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips now!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

Join Tek-Tips
*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

LINK TO THIS FORUM!

Add Stickiness To Your Site By Linking To This Professionally Managed Technical Forum.
Just copy and paste the
code below into your site.

Partner With Us!

"Best Of Breed" Forums Add Stickiness To Your Site
Partner Button
(Download This Button Today!)

Feedback

"...This was the ONLY place that I could find information that I could use to resolve the problem. So thanks once again to member TomSark and the SQL forum!..."

Geography

Where in the world do Tek-Tips members come from?

Set up conditional restriction in SP Query?Helpful Member! 

Amesville (Programmer)
10 May 12 16:34

Hi Folks

I'm trying to write a stored proc that will return a filtered result if the result of a subquery has data in it, or unfiltered if it doesn't.

So basically it would be SELECT A, B, C FROM TableX;

but if a subquery (SELECT D FROM TableY WHERE E = @Par1;) returns rows, the query should read:

SELECT A, B, C FROM TableX WHERE C IN (SELECT D FROM TableY WHERE E = @Par1);

...But I am not sure how to set this up!

Can anyone offer some help? Thanks.

Craig

Qik3Coder (Programmer)
10 May 12 19:23

Need a little more clarity, so I'm going to use a concrete example.

Select C.*
from dbo.Customers c
WHERE
c.ID in (Select o.CustomerID from dbo.Orders o where o.CustomerID = @CustomerID)
--This is will then select ALL customers
OR @CustomerID is null

Let me know if that doesn't make sense.
You can add a conditional statement, with an

if(@CustomerID is null)
BEGIN
SELECT ...
END
ELSE
BEGIN
SELECT ...
END

Lodlaiden

You've got questions and source code. We want both!
Oh? That? That's not an important password. - IT Security Admin (pw on whiteboard)

Helpful Member!  markros (Programmer)
10 May 12 21:15

CODE

IF exists (select 1 FROM TableY WHERE E = @Par1)

SELECT A, B, C FROM TableX WHERE E = @Par1;
ELSE
SELECT A, B, C FROM TableX

PluralSight Learning Library

Amesville (Programmer)
11 May 12 13:15
Thanks, that should do it! Very much appreciated.

Craig

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close