在SQL Server中,如何创建while循环

时间:2016-12-11 13:08:38

标签: sql sql-server sql-server-2008

我有以下内容: 我使用select从表中获取Id如下:

Select Id from t 

数据将是这样的:

id  
DG1 
FS2
DD4

我想使用while或case将结果传递给以下sql语句 取决于select语句的结果

SELECT f.age_days, f.Body_wt,f.Act_Fcr_Day,f.Act_Growth ,
f.growth_gm as Growth ,f2.growth_gm as Growth1,
   COALESCE(
   (
   SELECT TOP 1 Body_wt
   FROM [dbo].[Broiler_Farms_Data] mi
   WHERE mi.Age_Days > f.Age_Days and     mi.flock_id = ??????
   ORDER BY
         Age_Days   
   ), 0) - f.Body_wt AS diff
FROM [dbo].[Broiler_Farms_Data] f

我该怎么做。

感谢

2 个答案:

答案 0 :(得分:0)

我发现使用outer apply

更容易理解这种逻辑
SELECT f.age_days, f.Body_wt, f.Act_Fcr_Day, f.Act_Growth,
       f.growth_gm as Growth, f2.growth_gm as Growth1,
       (COALESCE(mi.Body_wt, 0) - f.Body_wt0 AS diff
FROM [dbo].[Broiler_Farms_Data] f OUTER APPLY
     (SELECT TOP 1 mi.*
      FROM [dbo].[Broiler_Farms_Data] mi
      WHERE mi.Age_Days > f.Age_Days and mi.flock_id = ??????
      ORDER BY mi.Age_Days   
     ) mi;

然后,如果我理解正确:

SELECT t.id, f.age_days, f.Body_wt, f.Act_Fcr_Day, f.Act_Growth,
       f.growth_gm as Growth, f2.growth_gm as Growth1,
       (COALESCE(mi.Body_wt, 0) - f.Body_wt0 AS diff
FROM [dbo].[Broiler_Farms_Data] f CROSS JOIN
     (Select Id from t
     ) t OUTER APPLY
     (SELECT TOP 1 mi.*
      FROM [dbo].[Broiler_Farms_Data] mi
      WHERE mi.Age_Days > f.Age_Days and mi.flock_id = t.id
      ORDER BY mi.Age_Days   
     ) mi;

这还包括id中的SELECT,因为这似乎是可取的。

答案 1 :(得分:0)

不建议在VARCHAR列中使用聚合函数。如果您有可以使用的主键或代理键,那么它将会很有帮助。使用以下查询来使用WHILE LOOP

DECLARE @Id VARCHAR(10) = ''
WHILE 1=1
BEGIN
    SELECT @Id = MIN(Id) from t WHERE Id > @Id
    IF @Id IS NULL
        BREAK
    SELECT f.age_days, f.Body_wt,f.Act_Fcr_Day,f.Act_Growth ,
    f.growth_gm as Growth ,f2.growth_gm as Growth1,
       COALESCE(
       (
       SELECT TOP 1 Body_wt
       FROM [dbo].[Broiler_Farms_Data] mi
       WHERE mi.Age_Days > f.Age_Days and     mi.flock_id = @Id
       ORDER BY
             Age_Days   
       ), 0) - f.Body_wt AS diff
    FROM [dbo].[Broiler_Farms_Data] f
END