Solved

SQL Server conditional Where in select

Posted on 2013-02-05
2
526 Views
Last Modified: 2013-02-05
I have a select that I want to have a conditional where statement

Passing in a variable 'P' or 'B'

I have a table with 4 columns
id    dText     Bill     Pay
1     Hours     1          0
2     Hrs-Reg  0          1

etc

When @var = 'P'
return  data where Pay = 1

when @var = 'B'
return data where Bill = 1

I have this which works...just wondering if I can streamline it
ALTER PROCEDURE usp_HoursTrackingDetailHoursGet2
			(
				@type VARCHAR(1)
			)
AS
BEGIN
	SET NOCOUNT ON;

		IF @type = 'B'
		BEGIN
			SELECT	hsid ,
					Definition 
			FROM	dbo.HoursTracking_SID_Definitions
			WHERE	Bill = 1
			ORDER BY def DESC, sort ASC
		END
		ELSE
		BEGIN
			SELECT	hsid ,
					Definition 
			FROM	dbo.HoursTracking_SID_Definitions
			WHERE	Pay = 1			
			ORDER BY def DESC, sort ASC
		END
END

Open in new window

0
Comment
Question by:lrbrister
2 Comments
 
LVL 65

Accepted Solution

by:
Jim Horn earned 500 total points
ID: 38856903
Copy-paste the below into your SSMS, verify it works how you want, then modify to suit your needs.

CREATE TABLE #foo (id int, dText char(10), bill bit, pay bit)

INSERT INTO #foo (id, dText, bill, pay)
VALUES (1, 'Hours', 1, 0), (2, 'Hrs-Reg', 0, 1)

Declare @var char(1) = 'B'

SELECT id, dText, Bill, Pay
FROM #foo
WHERE (@var = 'P' AND bill=1) OR (@var = 'B' AND pay = 1)

Open in new window

0
 

Author Closing Comment

by:lrbrister
ID: 38857009
Perfect!

Remind me to buy you a sody-pop sometime
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Introduction SQL Server Integration Services can read XML files, that’s known by every BI developer.  (If you didn’t, don’t worry, I’m aiming this article at newcomers as well.) But how far can you go?  When does the XML Source component become …
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
Viewers will learn how the fundamental information of how to create a table.
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now