SQL Server存储过程来比较日期

时间:2015-06-11 20:11:28

标签: sql sql-server stored-procedures

我想从表格中选择所有日期,并希望查看表格中的任何日期是否小于特定日期。

当我这样做时

select DateEntered from Table1 where ID = 4

结果:

2015-05-12 06:21:43.600
2018-07-12 06:21:43.600

现在我想要回复'-1'如果任何日期小于'2015-06-11 06:21:43.600',否则'1'。

所以,在这里我应该得到-1。

如何编写该存储过程?

3 个答案:

答案 0 :(得分:0)

select case 
    when DateEntered  < '2015-06-11 06:21:43.600' then '-1'
    else '1'
       end
from Table1 where ID = 4

答案 1 :(得分:0)

如果您要编写存储过程,它看起来与此类似:

USE mydb
GO

CREATE Procedure dbo.MyProcedure @CurrentDate Date
AS
BEGIN
SET @CurrentDate = GETDATE()

SELECT
 CASE 
   WHEN DateEntered < @CurrentDate THEN -1
   WHEN DateEntered >= @CurrentDate THEN 1
 END AS myvalue
FROM Table1 
WHERE ID = 4

END

GO

答案 2 :(得分:0)

CREATE PROCEDURE [dbo].[prcName]
(
    @machineId INT

)
AS
BEGIN
SELECT  

        Case when CONVERT(VARCHAR(8), M.EndDate, 112)<CONVERT(VARCHAR(8), GETDATE(), 112) then 'InActive' else 'Your Value 1' End as 'Your Value 2' 
FROM [dbo].[MachineUsageCost] M WITH(NOLOCK)

WHERE   (@machineUsageCostId IS NULL OR @machineUsageCostId = MachineUsageCostId) AND MachineId=@machineId  
        and M.IsActive=1
 END