简体   繁体   English

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

[英]In SQL Server, how to create while loop

I Have the following : I used the select to got the Id from table as follow : 我有以下内容:我使用select从表中获取ID,如下所示:

Select Id from t 

data will be like this: 数据将如下所示:

id  
DG1 
FS2
DD4

I want to pass result the result to the following sql statement using while or case Depend of the result of the select statement 我想将结果通过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

How can I do it . 我该怎么做 。

thanks 谢谢

I find this type of logic easier to follow with outer apply : 我发现使用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;

Then, if I understand correctly: 然后,如果我正确理解:

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;

This also includes the id in the SELECT , because that seems desirable. 这也包括SELECTid ,因为这似乎是理想的。

Aggregate functions in VARCHAR columns are not advised. 不建议在VARCHAR列中使用聚合函数。 If you have a Primary Key or a surrogate key which can be used, then it will be helpful. 如果您有可以使用的主键或代理键,则将很有帮助。 Use the below query to use WHILE LOOP . 使用以下查询来使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM