Solved

SQL Server conditional Where in select

Posted on 2013-02-05
2
532 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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article I will describe the Copy Database Wizard method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Via a live example, show how to shrink a transaction log file down to a reasonable size.

790 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