在动态查询中循环
While LOOP IN Dynamic QUERY
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
我收到错误:
Conversion failed when converting the varchar value 'Select Style_Color, Style_Color_Desc as Description,RPT, Weeks, Select STORE_ID from table_name where id= to data type int.
有时当我做一些更改时出现此错误
Cannot perform an aggregate function on an expression containing an aggregate or a subquery
谁能帮我如何在动态查询中声明 while 循环?
在您的情况下,您可以使用两种变体:
1) 使用CAST
或CONVERT
函数
-- 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'' ')
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
我收到错误:
Conversion failed when converting the varchar value 'Select Style_Color, Style_Color_Desc as Description,RPT, Weeks, Select STORE_ID from table_name where id= to data type int.
有时当我做一些更改时出现此错误
Cannot perform an aggregate function on an expression containing an aggregate or a subquery
谁能帮我如何在动态查询中声明 while 循环?
在您的情况下,您可以使用两种变体:
1) 使用CAST
或CONVERT
函数
-- 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'' ')