0

I would like to know if I can declare a variable where its contents is the name of a column, I tried the example below and it did not work.

DECLARE @P1 VARCHAR(3) 
SET @P1 = 'CPF'

SELECT * 
FROM dbo..table A 
WHERE @P1 = '123456789'

The following is a sample table:

CPF            NAME
-----------------------
123456789      Luis
987654321      Rafael
4

2 Answers 2

0

You can use dynamic sql and concatenate your variable into the statement. Then you execute the statement you build. You'll also have to escape the single quotes in the query variable.

DECLARE @P1 VARCHAR (3) = 'CPF'

DECLARE @sqlQuery  NVARCHAR(MAX) = N'
SELECT * 
FROM dbo.table A 
WHERE ' + @P1 + ' = ''123456789''
'
EXEC(@sqlQuery)
Sign up to request clarification or add additional context in comments.

1 Comment

This is a good example of dynamic SQL that is vulnerable to SQL injection. It would be hard, however, to inject malicious SQL into a 3-character field. :) Also, you are likely to have control over the column names, so it may be safe to do this.
0

You need to create dynamic select statement for that. [However , using dynamic SQL has it's own challenges such as possible SQL Injection attack].

see below -

DECLARE @P1 VARCHAR (10) = 'Column4' --This is Table column name , so you can give as per your table 
DECLARE @sqlQuery NVARCHAR(MAX) = N'SELECT * FROM  [Table 1]  WHERE ' + @P1 + ' =11' 
--above statement you will modify as per your code.
EXECUTE sp_executesql @sqlQuery

1 Comment

It is important to note that this opens you up to SQL injection attacks unless you are very carefully and thoroughly scrubbing any user inputted values.

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.