0

I'm working in a dynamic query where i need to add a column to the query if the parameter value is false.

//SQL:

SET @FilterExp = 'SELECT * from tblName where ptblnFlag = '+Convert(varchar(2),@blnFlag)+') as tbl where 1=1'+ COALESCE(NULLIF( CONVERT(varchar(8000), @FilterExp),''), '')

In the above query i need to check if the @blnFlag is false then the column can be added in the where condition. If true it need not to be there.

Something like if the condition is false it should return all values and if true the result set is based on the condition.

1 Answer 1

1

You just need AND/OR operator's no need of Dynamic query here

SELECT *
FROM   tblName
WHERE  ( ptblnFlag = @blnFlag
         AND @blnFlag = 0 )
        OR @blnFlag = 1 

May be am wrong with variable names but logic will be same

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

3 Comments

Its some big query which i have minimized to get better understanding.
@SanthoshKumar Ok, Whether my answer is helpful or not. If no, then change the question like this. Don't use dynamic sql in question. Just say like If @blnFlag = 0 then select query should be like select * from... if @blnFlag <> 0 then select query should be like select * from...
Your logic worked. I have few subqueries and more complex conditions and that's why i mentioned dynamic query. Thanks for your time.

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.