Reputation: 127
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..
Upvotes: 0
Views: 87
Reputation: 5253
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.
Upvotes: 0
Reputation: 35790
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.
Upvotes: 1