根据case语句显示更新结果

时间:2017-10-19 20:47:35

标签: sql sql-server tsql sql-server-2012

我想显示受以下代码影响的更新行数;

[SLComposeViewController composeViewControllerForServiceType:@"com.linkedin.LinkedIn.ShareExtension"];

输出应为:

UPDATE [document]
SET CalculatedTime = CASE WHEN DATEPART(hh, PrimaryDate) < 9 
                             THEN 'Pre-9AM'
                             ELSE CASE WHEN datepart(hh, PrimaryDate) >= 9 AND datepart(hh, PrimaryDate) <= 18 
                                          THEN 'Between 9AM-6AM' 
                                          ELSE CASE WHEN datepart(hh, PrimaryDate) > 18 
                                                       THEN 'Post-6PM' 
                                                       ELSE '' 
                                               END
                                  END 
                     END

感谢任何帮助!

2 个答案:

答案 0 :(得分:3)

首先,不需要嵌套for j in range(epoch):

CASE

其次,如果您希望每个案例都可以使用:

update [document]
SET CalculatedTime = 
       case when DATEPART(hh,PrimaryDate) < 9 then 'Pre-9AM'
            when datepart(hh,PrimaryDate) >= 9 
                 AND datepart(hh,PrimaryDate) <= 18 then 'Between 9AM-6AM' 
            when datepart(hh,PrimaryDate) > 18 then 'Post-6PM' 
            else '' 
       end ;

它会起作用,因为你更新整个表。

使用SELECT CalculatedTime, COUNT(*) FROM [document] GROUP BY CalculatedTime;

MERGE

答案 1 :(得分:0)

您可以在表格中使用UPDATE OUTPUT。

Declare @document table (CalculatedTime varchar(50));

    UPDATE [document]
        SET CalculatedTime = 
               Case when DATEPART(hh,PrimaryDate) < 9 then 'Pre-9AM'
                    when datepart(hh,PrimaryDate) >= 9 
                         AND datepart(hh,PrimaryDate) <= 18 then 'Between 9AM-6AM' 
                    when datepart(hh,PrimaryDate) > 18 then 'Post-6PM' 
                    else '' 
               End 
            OUTPUT INSERTED.CalculatedTime INTO @document

    SELECT CalculatedTime as TimeCalculation, COUNT(*) as Count
        FROM @document
            GROUP BY CalculatedTime;