0

For EXAMPLE i have this query from C#:

string query = "SELECT * FROM [dbo].[users]" +
               "WHERE " + ((class == "ADMIN") ? "class_id = 0;" : "class_id <> 0;")

My TASK was suppose to make this code as a stored proc so i used this code:

DECLARE @class VARCHAR(25);
IF @class = "ADMIN"
BEGIN
    SELECT * FROM [dbo].[users]
    WHERE class_id = 0;
END

ELSE
BEGIN
    SELECT * FROM [dbo].[users]
    WHERE class_id != 0;
END

How can i shorten my T-SQL code without typing the SELECT * FROM [dbo].[users] all over again?.....

PS. I've used the DYNAMIC SQL Coding style but my team wouldn`t approve it..

2
  • 3
    Try this: SELECT * FROM users WHERE (@class = 'ADMIN' AND class_id = 0) OR (@class<> 'ADMIN' AND class_id <> 0) Commented Aug 14, 2015 at 3:02
  • I give style points to Felix's solution to shorten the code but I discourage this solution as you put the burden on the query processor to handle your two cases unnecessarily at runtime. The original pattern eliminates runtime lookup work as the OR is often fully evaluated. Commented Aug 14, 2015 at 3:37

2 Answers 2

1

You can shorten like this:

SELECT * FROM [dbo].[users]
WHERE (@class = 'ADMIN' AND class_id = 0) OR (@class <> 'ADMIN' AND class_id <> 0)

2 notes:

Use <> instead of != because first is standard SQL.

Always use parametrized queries because of SQL injections.

Sign up to request clarification or add additional context in comments.

1 Comment

Plus read excellent article by Erland Sommarskog Dynamic Search Conditions in T‑SQL
0

One more way to do this:

SELECT Class_id, Class_Name FROM 
(
 select * 
 ,case when class_id = 0 then 'Admin' --Add as many conditions as needed
 --when class_id = 1 then 'Teacher'
 else '' end as [ClassType]
 from dbo.Users
)A WHERE ClassType = @a

You can add multiple conditions easily this way in the CASE statement. Illustrated one in the comments.

Comments

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.