在LOOP IN Dynamic QUERY中

时间:2018-04-03 19:08:24

标签: sql sql-server stored-procedures dynamicquery

BEGIN
DECLARE @sqlQuery VARCHAR(MAX)
SET @sqlQuery ='Select Style_Color, Style_Color_Desc as Description, 
 RPT, Weeks,  '

DECLARE @cnt INT = 1
DECLARE @TblCount NVARCHAR(1000) = (SELECT COUNT(ID) FROM table_Name)            

WHILE @cnt <= @TblCount
BEGIN
    SET @sqlQuery = @sqlQuery + 'max(CASE WHEN Cluster_ID = (Select STORE_ID from Table_Name where id= '+@cnt+')
     then CAST(c.APS_Dev as decimal(10,2)) end) as ''APS Dev'' '


     SET @cnt = @cnt + 1
END

SET @sqlQuery = @sqlQuery+'                                          
 Minimum as Pres_Min  From table_Name '

PRINT(@SQLQuery)
END

我收到错误:

  

转换varchar值时转换失败&#39;选择Style_Color,Style_Color_Desc作为Description,RPT,Weeks,从table_name选择STORE_ID,其中id =到数据类型int。

有些时候我没有做任何更改来获取此错误

  

无法对包含聚合或子查询的表达式执行聚合函数

有人可以帮我解决如何在动态查询中声明while循环吗?

1 个答案:

答案 0 :(得分:0)

在您的情况下,您可以使用两种变体:

1)使用CASTCONVERT函数

-- CAST
SET @sqlQuery += 'max(CASE WHEN Cluster_ID = (Select STORE_ID from Table_Name where id= '+CAST(@cnt AS varchar(5))+')
then CAST(c.APS_Dev as decimal(10,2)) end) as ''APS Dev'' '

-- CONVERT
SET @sqlQuery += 'max(CASE WHEN Cluster_ID = (Select STORE_ID from Table_Name where id= '+CONVERT(varchar(5),@cnt)+')
then CAST(c.APS_Dev as decimal(10,2)) end) as ''APS Dev'' '

2)使用CONCAT函数进行字符串连接

SET @sqlQuery += CONCAT('max(CASE WHEN Cluster_ID = (Select STORE_ID from Table_Name where id= ',@cnt,')
then CAST(c.APS_Dev as decimal(10,2)) end) as ''APS Dev'' ')