如何在存储过程中应用转换

时间:2019-06-23 21:10:06

标签: sql sql-server ssrs-2012

我在不同的时间看到了此解决方案,但是我不确定在这种情况下如何应用此转化。请在下面查看错误消息和代码:

  

将varchar数据类型转换为datetime数据类型会导致值超出范围

     

从字符串转换日期和/或时间时转换失败。

代码:

ALTER PROCEDURE SP_Loans_to_Date 
    @ReportDate DATETIME   
AS
BEGIN
    DECLARE @DayofWeek VARCHAR(100),
            @BeginofWeek DATE,
            @BeginofMonth DATE,
            @BeginofYear DATE

    SET @DayofWeek = DATENAME(DW, @ReportDate)
    SET @BeginofWeek = (SELECT 
                            CASE 
                               WHEN @DayofWeek = 'Sunday' 
                                  THEN DATEADD(DD, 0, @ReportDate)
                               WHEN @DayofWeek = 'Monday' 
                                  THEN DATEADD(DD, -1, @ReportDate)
                               WHEN @DayofWeek = 'Tuesday' 
                                  THEN DATEADD(DD, -2, @ReportDate)
                               WHEN @DayofWeek = 'Wednesday' 
                                  THEN DATEADD(DD, -3, @ReportDate)
                               WHEN @DayofWeek = 'Thursday' 
                                  THEN DATEADD(DD, -4, @ReportDate)
                               WHEN @DayofWeek = 'Friday' 
                                  THEN DATEADD(DD, -5, @ReportDate)
                               WHEN @DayofWeek = 'Saturday' 
                                  THEN DATEADD(DD, -6, @ReportDate) 
                            END BeginofWeek)
    SET @BeginofMonth = (SELECT 
CONVERT(DATETIME, CONVERT(VARCHAR(100), DATEPART(MM, @ReportDate)) + '1'+ 
CONVERT(VARCHAR(100), DATEPART(YY, @ReportDate))))
    SET @BeginofYear =  (SELECT ('1/1' + 
                                CONVERT(VARCHAR(100), DATEPART(YY, @ReportDate))))

    SELECT 
        SSN, LoanDate,
        CASE
           WHEN LoanDate >= @BeginofWeek AND LoanDate <= @ReportDate 
              THEN 'WeektoDate'
           WHEN LoanDate >= @BeginofWeek AND LoanDate <= @ReportDate 
              THEN 'MonthtoDate'
           WHEN LoanDate >= @BeginofWeek AND LoanDate <= @ReportDate 
              THEN 'YeartoDate' 
           ELSE NULL 
        END ToDate,
        CASE
           WHEN LoanDate >= @BeginofWeek AND  LoanDate <= @ReportDate 
              THEN 1
           WHEN LoanDate >= @BeginofWeek AND  LoanDate <= @ReportDate 
              THEN 2
           WHEN LoanDate >= @BeginofWeek AND  LoanDate <= @ReportDate 
              THEN 3 
           ELSE NULL 
        END ToDateOrder
    FROM
        [dbo].[Dim_Loan];

END

1 个答案:

答案 0 :(得分:0)

我的建议是避免不必要的date-> string-> date转换,您可以通过更简单的方式获取这些值

DECLARE @DayofWeek INT,
        @BeginofWeek DATE,
        @BeginofMonth DATE,
        @BeginofYear DATE

SET @DayofWeek = DATEPART(DW, @ReportDate)
SET @BeginofWeek = DATEADD(DAY, 1 - @DayofWeek, @ReportDate)
SET @BeginofMonth = DATEFROMPARTS(YEAR(@ReportDate), MONTH(@ReportDate), 1)
SET @BeginofYear = DATEFROMPARTS(YEAR(@ReportDate), 1, 1)