我尝试在存储过程中使用CASE
语句来选择datecolumn1
或datecolumn2
。
然后我需要选择其他列并将它们插入到临时表中以获得合规性到期报告。
我有以下
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
我知道这不正确但是很难看出我哪里出错了,有没有更好的方法来提供这些数据?
答案 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.statusdate
与P.enddate
具有相同的数据类型,或至少可以隐式转换为它。