[英]How to select dynamic column value from a table?
I have a table called "TableA" which has the following records: 我有一个名为“ TableA”的表,该表具有以下记录:
TableA: 表A:
ID Jan Feb
---- ----- -------
1 '01/12' '04/12'
Here I want to select any one of the column value from the table. 在这里,我想从表中选择任一列值。 But the column name is assigned to a variable. 但是列名称已分配给变量。 We don't know the exact column name. 我们不知道确切的列名。
For Example: 例如:
Declare @Month VARCHAR(20)
SET @Month = 'Feb'
Select @Month from TableA
It gives the Output as follows: 它给出的输出如下:
'Feb'
But the Desired Output is '04/12' 但是所需的输出是'04 / 12'
How to get the desired output? 如何获得所需的输出?
try this: 尝试这个:
Declare @Month VARCHAR(20)
SET @Month = QUOTENAME('Feb')
exec('Select '+@Month+' from TableA')
Use UNPIVOT
使用UNPIVOT
select months
from TableA
unpivot
(months for m in (Jan, Feb)) pvt
where m=@month
It's a much safer solution than dynamic SQL as it isn't vulnerable to a SQL Injection attack 它比动态SQL安全得多,因为它不容易受到SQL注入攻击的攻击
Use EXEC or sp_executesql 使用EXEC或sp_executesql
EXEC: 执行:
Declare @Month NVARCHAR(20)
SET @Month = 'Feb'
DECLARE @SQL NVARCHAR(4000)
SET @SQL = 'Select ' + @Month + ' from TableA'
EXEC(@SQL)
sp_executesql is preferable, as it parameterizes the variable: 最好使用sp_executesql,因为它将参数化变量:
DECLARE @SQL NVARCHAR(4000) SET @SQL = 'Select @Month from TableA' EXEC sp_executesql @SQL, N'@Month NVARCHAR(20)', @Month = 'Feb'
(This just returns the constant 'Feb' - column names can't be variables ) (这只是返回常量'Feb'-列名不能是变量)
Try this 尝试这个
Declare @colName VARCHAR(20)
SET @colName = 'Feb'
Exec('select '+ @colName+' from TableA')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.