简体   繁体   中英

SQL Server stored procedure to compare dates

I want to select all the dates from a table and want to find if any date from the table is less than a specific date or not.

When I do

select DateEntered from Table1 where ID = 4

Result:

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

Now I want to return '-1' if any date is less than '2015-06-11 06:21:43.600', else '1'.

So, here I should get -1.

How can I write that stored procedure?

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

If you are looking to write a stored procedure it would look similar to this:

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
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM