使用Case来确定col1或col2是否返回到存储过程中的Temp Table

时间:2018-03-26 08:53:38

标签: sql-server tsql stored-procedures case

我尝试在存储过程中使用CASE语句来选择datecolumn1datecolumn2

然后我需要选择其他列并将它们插入到临时表中以获得合规性到期报告。

我有以下

BEGIN
    DECLARE @Rangefrom DATE,
            @Rangetill DATE

    SET @Rangefrom = DATEADD(day, -50, GETDATE()) 
    SET @Rangetill = DATEADD(day, -90, GETDATE())

    CREATE TABLE #TempStatusTable
    (
         STATUSDATE DATE,
         NAME VARCHAR(50),
         Rangefrom DATE,
         Rangetill DATE,
         StatusID VARCHAR(10)
    )

    SELECT 
        statusdate = (CASE 
                         WHEN P.enddate IS NOT NULL 
                            THEN (SELECT CONVERT(DATE, P.EndDate, 103)
                                  FROM Applicants AS A 
                                  LEFT JOIN Person AS PE ON A.ApplicantId = PE.PersonID
                                  LEFT JOIN Placements AS P on PE.PersonID = P.Applicantid)
                         ELSE (SELECT CONVERT(DATE, A.statusdate, 103) 
                               FROM Applicants AS A 
                               LEFT JOIN Person AS PE ON A.ApplicantId = PE.PersonID
                               LEFT JOIN Placements AS P on PE.PersonID = P.Applicantid) 
                      END)
    SELECT                                      
        PE.Personname + ' ' + PE.Surname [Name],
        @rangefrom [Expiry warning from],
        @rangetill [Expiry warning till],
        A.Statusid
    INTO 
        #TempStatusTable 
    FROM  
        Applicants AS A 
    LEFT JOIN 
        Person AS PE ON A.ApplicantId = PE.PersonID
    LEFT JOIN 
        Placements AS P on A.applicantid = P.Applicantid

    SELECT * 
    FROM #TempStatusTable

我知道这不正确但是很难看出我哪里出错了,有没有更好的方法来提供这些数据?

1 个答案:

答案 0 :(得分:0)

您不能使用case作为流控制,它是一个表达式。 试试这个:

SELECT statusdate = CONVERT(DATE, CASE WHEN P.enddate IS NOT NULL THEN P.EndDate ELSE A.statusdate END, 103)
FROM Applicants AS A 
LEFT JOIN Person AS PE ON A.ApplicantId = PE.PersonID
LEFT JOIN Placements AS P on PE.PersonID = P.Applicantid

或更短,使用ISNULL

SELECT statusdate = CONVERT(DATE, ISNULL(P.enddate, A.statusdate), 103)
FROM Applicants AS A 
LEFT JOIN Person AS PE ON A.ApplicantId = PE.PersonID
LEFT JOIN Placements AS P on PE.PersonID = P.Applicantid

这两个选项都要求A.statusdateP.enddate具有相同的数据类型,或至少可以隐式转换为它。