1

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'

1
  • you can do like this if you can SELECT * FROM TBL T WHERE coulmn_nmae = @PT_CONST Commented Nov 12, 2014 at 8:19

1 Answer 1

1

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'
Sign up to request clarification or add additional context in comments.

2 Comments

dont know the column names..so your solution is not feasible
Then you have no solution without dynamic SQL. SQL server query processor needs to know column names at compile time, there is no way around it. You could check presence of columns before building your dynamic SQL to avoid errors of course.

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.