动态SQL查询返回列名而不是值

时间:2015-04-15 18:09:01

标签: sql sql-server dynamic-sql

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

有人可以告诉或指导我获取价值吗?我将不胜感激。

HubFinal

  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

1 个答案:

答案 0 :(得分:0)

正如@Sean Lange告诉你的那样......不建议在sql server中循环,因为它会达到性能(你应该找到另一种方法来解决你的问题),但是如果你想得到这个值您可以像这样使用动态列名称

因为我不知道您正在使用的数据类型我假设它是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)