简体   繁体   中英

MS SQL Convert date to short

I am trying to get all of the records from a table where the ExpiryDate field is exactly one month away.

The problem however is that the ExpiryDate is stored with the hours, minutes and seconds. How do I therefore say - Get me all of the records from my table where the ExpiryDate (dd/MM/yyyy) is one month ahead of now (dd/MM/yyyy).

This is what I have currently:

SELECT *    FROM dbo.Custom_MembershipTransaction mt (nolock)
WHERE       mt.ExpiryDate = DATEADD(MONTH, 1, GETDATE())
AND         mt.IsComplete = 1;

Try this:

SELECT *    FROM dbo.Custom_MembershipTransaction mt (nolock)
WHERE       convert(varchar, mt.ExpiryDate, 102) = convert(varchar, DATEADD(MONTH, 1, GETDATE()),102)
AND         mt.IsComplete = 1;

You need some buffertime like

SELECT *    FROM dbo.Custom_MembershipTransaction mt (nolock)
WHERE       mt.ExpiryDate < DATEADD(MONTH, 1, GETDATE())
AND         mt.ExpiryDate > DATEADD(DAY, -1, DATEADD(MONTH, 1, GETDATE()))
AND         mt.IsComplete = 1;

This will get you all recors that have an expiredate between 1 month ahead an (1 month - 1 day) ahead.

SELECT *    FROM dbo.Custom_MembershipTransaction mt (nolock)
WHERE       mt.ExpiryDate >= DATEADD(DAY, DATEDIFF(DAY, 0, DATEADD(MONTH, 1, GETDATE())), 0)
AND         mt.ExpiryDate < DATEADD(DAY, DATEDIFF(DAY, 0, DATEADD(MONTH, 1, GETDATE()) + 1), 0)
AND         mt.IsComplete = 1;

I didn't make operation on ExpiryDate as it might be used by an index

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