S M
S M

Reputation: 159

Dynamic query to select column based on the condition

Is it possible to select column based on the condition for dynamic queries. If condition is false, then it should not select that column. I want to write below as a dynamic query.

DECLARE @param varchar(10),
SELECT A, 
IF (@param = 'U')
B = A-2, '
From Table tb

Upvotes: 2

Views: 3380

Answers (2)

Zhorov
Zhorov

Reputation: 29943

You may start with this:

-- Declarations
DECLARE 
    @param varchar(10),
    @stm nvarchar(max),
    @err int

-- Parameter value
SET @param = 'U' -- or another value

-- Statement
SET @stm = N'SELECT ColumnA'
IF (@param = 'U') SET @stm = @stm + N', ColumnB'
SET @stm = @stm + N' FROM YourTable'

-- Execution
EXEC @err = sp_executesql @stm
IF @err = 0 PRINT 'OK'
ELSE PRINT 'Error'

Upvotes: 4

jawahar N
jawahar N

Reputation: 482

We can able to get the columns based on condition. For this we need CASE.

Here, I have added a sample code,

SELECT
    CASE WHEN @param=1 THEN UserFullName ELSE firstName END as userName
FROM users

Please take it.

Upvotes: 0

Related Questions