Reputation: 873
Declare @tempvar as Varchar(10)
Set @tempvar='true'
select dbo.InformationTable.Name,dbo.InformationTable.Address,dbo.InformationTable.FavoriteDish
from dbo.InformationTable
I want to show dbo.InformationTable.FavoriteDish
column only when @tempvar
is set to true
,else it will not include in select statement?How can i achieve this.Thanks.
Upvotes: 2
Views: 81
Reputation: 10478
Unfortunately there is no efficient way to conditionally exclude a column from a SELECT
query.
You can either do it this way:
DECLARE @tempvar AS VARCHAR(10)
SET @tempvar='true'
IF @tempvar = 'true'
BEGIN
SELECT
dbo.InformationTable.Name,
dbo.InformationTable.Address,
dbo.InformationTable.FavoriteDish
FROM
dbo.InformationTable
END
ELSE
BEGIN
SELECT
dbo.InformationTable.Name,
dbo.InformationTable.Address
FROM
dbo.InformationTable
END
Or, if you don't mind the column descending anyway as part of the resultset (with NULL
values), like this:
SELECT
dbo.InformationTable.Name,
dbo.InformationTable.Address,
CASE
WHEN @tempvar = 'true' THEN
dbo.InformationTable.FavoriteDish
ELSE NULL
END FavoriteDish
FROM
dbo.InformationTable
You also could build your query dynamically in a VARCHAR
variable and pass it to the EXEC
method:
DECLARE @myquery VARCHAR(1000)
/*
Build your query here on your own conditions
*/
EXEC(@myquery)
I strongly advise against the last one, though, because it comes with multiple tradeoffs.
Hope that helps.
Upvotes: 1