2015-10-30 102 views
-1

我有如下的存储过程:如果没有开始日期和结束日期的记录,存储过程?

CREATE Procedure [dbo].[GetSleepData] 
    @period varchar(30), 
    @fitbit varchar(6), 
    @customdate datetime null, 
    @startdate datetime null, 
    @enddate datetime null 

    as 


    if(@period = 'week') 
    Begin 
    Set @customdate = Getdate() 
     Select Sleepkey, fitbitid,totalMinutesAsleep,totalSleepRecords,totalTimeInBed, datetime from sleep where fitbitid = @fitbit and 
     datetime <[email protected] datetime= @customdate - 7 
    End 

    else if(@period = 'month') 
    Begin 
    Set @customdate = Getdate() 
     Select Sleepkey, fitbitid,totalMinutesAsleep,totalSleepRecords,totalTimeInBed, datetime from sleep where fitbitid = @fitbit and 
     datetime<= @customdate and datetime >= @customdate - 30 
    End 

这是工作的罚款。我需要在select语句中添加一个if子句。它应该是这样的:

如果startDate和/或endDate没有记录,它应该添加一个记录,其中的值为零。

+0

你应该看看这篇文章讨论这样的查询与多个执行路径。 http://sqlinthewild.co.za/index.php/2009/09/15/multiple-execution-paths/ –

+0

为什么比较字符串而不是日期? – lad2025

回答

2

首先,您可以将您的对帐单合并到一个SELECT

其次考虑使用DATEADD(d, -number, @customdate)的减法天日期,而不是@customdate - 7

CREATE Procedure [dbo].[GetSleepData] 
    @period  varchar(30), 
    @fitbit  varchar(6), 
    @customdate datetime = null, 
    @startdate datetime = null, 
    @enddate  datetime = null 
AS 
BEGIN 
SET NOCOUNT ON; 

-- you should here validate @period like 
-- IF @period NOT IN ('week', 'month') 
--  RAISEERROR(....) /THROW ...; 

SET @customdate = GETDATE(); 

SELECT Sleepkey, fitbitid,totalMinutesAsleep, 
     totalSleepRecords,totalTimeInBed, [datetime] 
INTO #temp 
FROM sleep 
WHERE fitbitid = @fitbit 
    AND [datetime] <= @customdate 
    AND [datetime] >= @customdate - (CASE @period 
            WHEN 'week' THEN 7 
            WHEN 'month' THEN 30 
            ELSE NULL --??? what if period is different 
           END; 

IF NOT EXISTS (SELECT 1 FROM #temp) 
BEGIN 
    SELECT 0 AS Sleepkey, 0 AS fitbitid, 0 AS totalMinutesAsleep, 
     0 AS totalSleepRecords, 0 AS totalTimeInBed, NULL AS [datetime] 
END 
ELSE 
BEGIN 
    SELECT Sleepkey, fitbitid,totalMinutesAsleep, 
      totalSleepRecords,totalTimeInBed, [datetime] 
    FROM #temp; 
END 

END 

不要将其命名像数据类型列:datetime应该被引用[datetime]

+1

伟大的解决方案!谢谢百万小伙子...... – sony

+0

@sony不客气:) – lad2025

相关问题