动态 SQL 查询 returns 列名而不是值

Dynamic SQL Query returns column name instead of value

我正在尝试创建一些动态传递列名的查询,但由于某种原因返回的是列名而不是值。 我对这种技术不是很熟悉,目前 @cmd 是空的,因为在我编写动态查询之前我想确保我将传递正确的参数。换句话说,我想打印 A1 列中的值。

任何人都可以告诉我或指导我获取价值吗?我将不胜感激任何帮助。

最终集线器

  id    Cart      PO              A1               A1E  
  ----------------------------------------------------------
  01    Cart1     24432     upc1,1/25/2016,1      Available
  -----------------------------------------------------------
  02    Cart2     24888     upc10,1/25/2030,1     No Available

查询

WHILE (@i <= 1)
BEGIN

--  get Column Name Example A1
    SET @Compartment = (SELECT compartment FROM @Compartment_table WHERE idx = @i);

--  get data from HUBFINAL to insert into HUBTEMP
    SET @PO = (Select PO FROM HubFinal Where CartPlate =@CartPlate);

--  pass dynamically the comlumn name, in this case A1
    SET @CompValue = (Select  @Compartment From HubFinal Where  CartPlate =@CartPlate);


Print @Compartment 
Print @PO
Print @CompValue 



--insert to final table
         Declare @cmd nvarchar(4000) =
              -- do something with values gotten above
         EXEC(@cmd)


-- increment counter for next compartment
    SET @i = @i + 1

END

输出

-- this is what is printed

  A1
  24432
  A1

正如@Sean Lange 告诉你的那样......不建议在 sql 服务器中循环,因为它会影响性能(你应该找到另一种方法来解决你的问题),但如果你想获得动态列名的值你可以这样做

因为我不知道您正在使用的数据类型,所以我假设它是 NVARCHAR

DECLARE @value NVARCHAR(MAX);
SET @CompValue = CONVERT(NVARCHAR(MAX), 'Select  @val='+ @Compartment + ' From HubFinal Where CartPlate = @CartPlate')

EXECUTE sp_executesql @CompValue, N'@CartPlate NVARCHAR(MAX),@val NVARCHAR OUTPUT', @CartPlate = @CartPlate, @val= @value OUTPUT

PRINT(@value)