Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
in my query in where condition i am filtering one column name campus.so if campus is 5 then select the record with campus as 5 otherwise select all records.how to write query?

query like:

SQL
select code,name from table1 where campus=(//here i want to implement the logic)
Posted
Updated 19-Feb-13 0:15am
v3
Comments
Ankur\m/ 19-Feb-13 7:02am    
" if campus is 5 then select the record with campus as 5 otherwise select all records"
What do you mean here? Is campus a column of table1 or does it belong to other table?
If it is, 'select code,name from table1 where campus=5' will give you all rows with column = 5.
Similarly, 'select code,name from table1 where campus <> 5' will give you all rows with column not equal to 5.
josh-jw 19-Feb-13 7:19am    
i want to retrieve all the records with a condition that in where clause like if my input parameter @campus is '' select all the record.otherwise Campus=@campus
Ankur\m/ 19-Feb-13 7:44am    
Use the 'Reply' link beside a comment to reply to a post. Otherwise the poster doesn't get notified and he may never see your reply.
Ankur\m/ 19-Feb-13 7:46am    
Are you using a stored procedure to execute this query?

Better you go for dynamic sql.Suppose you have a department table which has 2 columns(Id, Name)
The code is as follows
SQL
declare @Id int = 3;
declare @sql nvarchar(max) = 'SELECT Id,Name FROM Departments';

IF @Id = 2
   SET @sql += ' WHERE Id='+ cast(@id as varchar(10));

EXEC sp_ExecuteSQL @sql;
 
Share this answer
 
Create a stored procedure, like this:
SQL
CREATE PROCEDURE GetCamousByID
    @id INT
AS
BEGIN

    DECLARE @qry NVARCHAR(300)

    SET @qry = 'SELECT * FROM table1 '
    IF (@id = 5)
        SET @qry = @qry + 'WHERE CAMPUS = ' + @id

    EXEC(@qry)

END
 
Share this answer
 
Hi,
You can try this style as well:
DECLARE @campus INT = (
            SELECT campus
            FROM   table1
            WHERE  campus = 5
        )

SELECT code,
       NAME
FROM   table1
WHERE  campus = COALESCE(@campusId, '') = ''
       OR  campus = @campus
 
Share this answer
 
Hi ,

Try like this

SQL
DECLARE @Campus INT =5

SELECT code,name
FROM table1
WHERE (Code=(CASE WHEN @Campus=5 THEN @Campus ELSE 0 END) OR @Campus <> 5)


Regards,
GVprabu
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900