如何使用SQL Select查询通过动态字段名称获取值

时间:2019-05-27 10:48:34

标签: sql sql-server sql-server-2008 sql-server-2008-r2

我正在基于该列名称传递动态列名称,以获取值,并且在我的表格下方

$("img").prop("alt", "This is some alt text");

Example1

Table_CandidateInfo

Id     Name        Age    City 

1      Mazhar      30     Gulbarga

20     Khan        29     Bidar

我无法通过Declare @ColumnName varchar(100), @Id int set @ColumnName='Age' set @Id=20 select * from Table_CandidateInfo where ID=@Id and 查询传递列名,因为列名是通过代码动态传递的。我的输出应该是

and

示例2:如果我的@ ColumnName ='City'和@ Id = 20,则输出应如下所示

29

2 个答案:

答案 0 :(得分:3)

我认为您的实际追求如下:

DECLARE @ColumnName sysname, @Id int;
SET @Id = 29;
SET @ColumnName = N'Age';

DECLARE @SQL nvarchar(MAX);
SET @SQL = N'SELECT ' + QUOTENAME(@ColumnName) + N' FROM dbo.Table_CandidateInfo WHERE Id = @Id;';
--PRINT @SQL; --Your debugging friend
EXEC sp_executesql @SQL, N'@Id int', @Id = @Id;

答案 1 :(得分:2)

A,您不能将标识符作为参数传递。您需要使用动态SQL:

f = False
out = []
for i in t:
    if i[1] == 'ORGANIZATION':
        if not f:
            out.append(i[0])
            f = True
        else:
            out[-1] += f' {i[0]}'
            f = False

print(out)
# ['Wall Mart', 'Thomas Cook']