?
Solved

SQL Server conditional Where in select

Posted on 2013-02-05
2
Medium Priority
?
539 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 66

Accepted Solution

by:
Jim Horn earned 2000 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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Ready to get certified? Check out some courses that help you prepare for third-party exams.
MSSQL DB-maintenance also needs implementation of multiple activities. However, unprecedented errors can hamper the database management. In that case, deploying Stellar SQL Database Toolkit ensures fast and accurate database and backup repair as wel…
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
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.
Suggested Courses

757 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