2
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.

1 Answer 1

1

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.

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

3 Comments

Thanks for your reply .Is there is no cool way instead of replicate the code?
The cool way might be using the third option I gave you, but as I said this is something I don't recommend. In T-SQL you must favor the efficient way over the cool way. Always.
IMHO you should ask yourself why you want to exclude the column at server level instead of having the client make the right query.

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.