Home > database >  Could you tell me how to put the string used it as a column name for sub queries?
Could you tell me how to put the string used it as a column name for sub queries?

Time:09-20

if a table tableA, there is a field name1, name2, score,
If you declare @ field nvarchar (50)
The set @ field='name1'
So how to realize the subquery in as a condition of the column is provided by the @ field?
Such as the above I will @ field assigned to 'name1', then the equivalent in
Select score from tableA where name1='aaa'? ,
But the problem is that, in essentially
Select score from tableA where '@ field'='aaa', is invalid, consult everybody how to deal with?

CodePudding user response:

Try to use the exec, but select score from tableA where the exec (' @ field ')='aaa' also complains, or format is wrong

CodePudding user response:

Essentially a reference dynamic SQL statements,
- name1 name2, score,
Declare @ field nvarchar (50)
The set @ field='name1'
Declare @ v_sql nvarchar (200)='select score from tableA where' ' ' '@ field' ' ' '=' ' ' 'aaa' "'
The exec @ v_sql;
Is probably wrote, specific you can search a dynamic SQL statement execution,



  • Related