DECLARE @dimension_ID int = 1; DECLARE @dimension_Content nvarchar(50); WHILE @dimension_ID <= (SELECT MAX([ID]) FROM [AP_Inventory].[dbo].[MD_Variation_Dimension]) BEGIN SET @dimension_Content = (SELECT [Dimension] FROM [AP_Inventory].[dbo].[MD_Variation_Dimension] WHERE [ID] = @dimension_ID); EXEC(' SELECT a.[CompanyCtry], a.[SBU], a.'+@dimension_Content+', a.[Inv_CM], b.[Inv_LM], ROW_NUMBER() OVER ( PARTITION BY a.[CompanyCtry], a.[SBU] ORDER BY ABS(a.[Inv_CM] - b.[Inv_LM]) DESC ) as RowNo INTO [AP_Inventory].[dbo].[Temp_vs_CY_LM] FROM ( SELECT [CompanyCtry], [SBU_2023] as [SBU], '+@dimension_Content+', SUM([TotalInv_EUR]) as [Inv_CM] FROM [AP_Inventory].[dbo].[Inv_Details_for_PowerBI] WHERE DATEDIFF(MONTH, DATEFROMPARTS([ReportYear], [ReportMonth], 1), GETDATE()) = 1 and [StockCategory] <> ''Vendor Consignment'' and '+@dimension_Content+' is not null GROUP BY [CompanyCtry], [SBU_2023], '+@dimension_Content+' ) as a, ( SELECT [CompanyCtry], [SBU_2023] as [SBU], '+@dimension_Content+', SUM([TotalInv_EUR]) as [Inv_LM] FROM [AP_Inventory].[dbo].[Inv_Details_for_PowerBI] WHERE DATEDIFF(MONTH, DATEFROMPARTS([ReportYear], [ReportMonth], 1), GETDATE()) = 2 and [StockCategory] <> ''Vendor Consignment'' and '+@dimension_Content+' is not null GROUP BY [CompanyCtry], [SBU_2023], '+@dimension_Content+' ) as b WHERE a.[CompanyCtry] = b.[CompanyCtry] and a.[SBU] = b.[SBU] and a.'+@dimension_Content+' = b.'+@dimension_Content+' ') EXEC(' UPDATE a SET a.[vs_CY_LM_Content] = b.'+@dimension_Content+', a.[vs_CY_LM_Content_Qty] = b.[Inv_CM], a.[vs_CY_LM_Delta_Qty] = b.[Inv_CM] - b.[Inv_LM] FROM [AP_Inventory].[dbo].[Calculate_Top_Variation_V4] as a, [AP_Inventory].[dbo].[Temp_vs_CY_LM] as b WHERE a.[Organization] = b.[CompanyCtry] and a.[SBU] = b.[SBU] and a.[Dimension] = '''+@dimension_Content+''' and a.[vs_CY_LM_Rank] = b.[RowNo] and DATEDIFF(MONTH, DATEFROMPARTS(a.[Report_Year], a.[Report_Month], 1), GETDATE()) = 1; '); DROP TABLE [AP_Inventory].[dbo].[Temp_vs_CY_LM]; SET @dimension_ID = @dimension_ID + 1; 在这段代码里面exec函数有什么意义呢,并且一整段函数有什么意义。
时间: 2023-10-12 19:04:49 浏览: 149
在这段代码中,EXEC函数用于执行动态SQL语句。动态SQL是指在运行时根据参数或条件构建SQL语句并执行。使用EXEC函数可以将字符串作为SQL语句执行,从而实现动态生成和执行SQL语句。
整个代码段的意义是根据不同的维度(Dimension)计算出与上个月(LM)相比的差值,并更新到目标表中。代码中的循环用于遍历每个维度,并根据维度的内容动态生成并执行SQL语句。
具体来说,代码中的第一个EXEC语句用于创建一个临时表,该临时表存储了当前月份(CM)与上个月(LM)之间的差值,并按照指定规则进行排序。这个临时表用于后续更新目标表中的相关字段。
第二个EXEC语句用于更新目标表,将临时表中计算得到的差值和相关维度内容更新到目标表中的相应字段。更新的条件是目标表中的组织(Organization)、业务单位(SBU)、维度(Dimension)以及排名(Rank)与临时表中的对应字段匹配。
最后,使用DROP TABLE语句删除临时表。
整个代码段的目的是根据不同维度计算出与上个月相比的差值,并将计算结果更新到目标表中。通过使用动态SQL语句,可以根据不同的维度内容动态生成和执行SQL语句,实现对目标表的灵活更新。
阅读全文