RobertKing
RobertKing

Reputation: 1911

use variable as a column name in sql

Is there any to use variable names as a column name in sql join, without using dynamic query?

I want to use it like below.

DECLARE @PT_CONST VARCHAR(MAX)

SELECT * FROM TBL T WHERE T.@PT_CONST='VAL'

Upvotes: 1

Views: 78

Answers (1)

Arvo
Arvo

Reputation: 10570

Directly not. If you know that your column name can be one of the predefined set, then you could use something like

... WHERE CASE @PT_CONST WHEN 'Col1' THEN Col1 WHEN 'Col2' THEN Col2 ... END = 'VAL'

Upvotes: 1

Related Questions