简体   繁体   English

如何从表中选择动态列值?

[英]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.

相关问题 如何创建 SQL 过程以从动态表中选择动态列 - How to create SQL procedure to select dynamic column from dynamic table where dynamic table 如何从表中选择取决于另一个表列中的值 - How to select from table depend on value from another table column MySQL从表中选择动态行值作为列名,从另一个表中选择值 - Mysql select dynamic row values as column name from a table and value from another table Select 值来自表名,其中表名存储为使用动态 SQL 的其他表中的列中的值? - Select value from a table name where table name is stored as a value in column in some other table using dynamic SQL? 如何检查/选择字符串是否包含表列值中的值? - How to check/select if a string contains value from a table column values? 如何基于Oracle中另一个表中的行的值选择列 - how to select a column based on the value of a row from another table in oracle 如何根据同一表列中的值在SQL中进行SELECT? - How to SELECT in SQL based on a value from the same table column? 如何从表的单个列中选择第一个非空值? - How to select first not null value from a single column in a table.? SQL Server:从动态值表中选择列不包含任何值的所有行 - SQL Server : select all rows where Column does not contain any value from dynamic table of values 如何从表一中选择一列,同时从表二中传递一列的值? - how to select one column from table one , while passing a value of column from table two?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM