将字符串转换为DateTime并在Where子句中使用转换-Da​​teDiff

时间:2019-12-16 07:28:56

标签: sql sql-server

我有一个包含日期的字符串列。我想将字符串转换为日期,以便可以提前使用日期逻辑。

我已经将字符串转换为DateTime,但是在Where子句中应用逻辑时,不允许我使用Column。

SELECT a.code,       
       CONVERT(DATETIME,b.[FieldValue],103) as [Date1]           
FROM   [dbo].employeedetail as A join [dbo].CustomeFieldDetail as B
on A.Id = B.EMployeeid
WHERE  a.empstatus = 1 
 AND B.CustomeFieldName = 'PASSPORT' AND
       ( Datediff(dd, Getdate(), Dateadd(yyyy, Datediff(yyyy, b.[Date1], 
         Getdate()) 
                + 
                1, b.[Date1])) 
         + 1 ) % 366 = 50 

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:3)

使用APPLY引入可重用的表达式。

SELECT a.code,       
       c.[Date1]           
FROM  [dbo].employeedetail as A 
JOIN  [dbo].CustomeFieldDetail as B ON A.Id = B.EMployeeid
CROSS APPLY (
   SELECT CONVERT(DATETIME,b.[FieldValue],103) as [Date1] 
) c
WHERE  a.empstatus = 1 
 AND B.CustomeFieldName = 'PASSPORT' AND
       ( Datediff(dd, Getdate(), Dateadd(yyyy, Datediff(yyyy, c.[Date1], 
         Getdate()) 
                + 
                1, c.[Date1])) 
         + 1 ) % 366 = 50 

更好的解决方案是将日期存储为DATE,DATETIME,而不是字符串。

答案 1 :(得分:1)

使用CTE会产生更紧凑的查询:

WITH B AS (
    SELECT *, CONVERT(DATETIME, [FieldValue], 103) AS [Date1]
    FROM [dbo].CustomeFieldDetail
    WHERE (CustomeFieldName = 'PASSPORT')
)
SELECT A.code, B.[Date1]
FROM [dbo].EmployeeDetail AS A JOIN B ON A.Id = B.EMployeeid
WHERE (A.empstatus = 1)
  AND (((DATEDIFF(dd, GETDATE(), 
         DATEADD(yyyy, DATEDIFF(yyyy, B.[Date1], GETDATE()) + 1, B.[Date1])) + 1)
        % 366) = 50)