I have a procedure that takes, among other things, start and end date parameters. These two parameters are optional inputs and default to NULL. What I would like to do is modify one of the current SELECT statements so that if the start and end dates are supplied it will return only the results between those two dates. I considered just throwing a CASE WHEN... in the WHERE statement but that that is messy and does not seem right. Is that the appropriate way to deal with this or is there something more efficient?
Existing SELECT clause:
SELECT do.OrdrNmbr AS 'Order Number',
mb.BOLNmbr AS 'BOL Number',
do.DlvryDt AS 'Deliver Date',
mh.Text3 AS 'Truck',
do.DlvrdQntty AS 'Gallons Delivered',
ba.BANme AS 'Carier Business Associate'
FROM dbo.DeliveryOrder AS do WITH (NOLOCK)
INNER JOIN dbo.ManifestBOL AS mb WITH (NOLOCK)
ON do.OrdrNmbr = mb.OrdrNmbr
INNER JOIN dbo.BusinessAssociate AS ba WITH (NOLOCK)
ON do.CrrrBAID = ba.BAID
INNER JOIN SRA.dbo.MovementDocument as md WITH (NOLOCK)
ON md.MvtDcmntExtrnlDcmntNbr = 'DOD' + CONVERT(VARCHAR, mb.OrdrNmbr)
INNER JOIN SRA.dbo.MovementHeader AS mh WITH (NOLOCK)
ON mh.MvtHdrMvtDcmntID = md.MvtDcmntID
WHERE mb.OrdrNmbr = @OrderNumber;
and the start/end dates would run against do.DlvryDt.
P.S. I know the table/column names are horrid but this is a 3rd party application the query is running against.
AS 'alias'syntax - this is deprecated (see sqlblog.org/2012/01/23/…). (2) Be careful declaring types likeVARCHARwithout length (see sqlblog.org/2009/10/09/…). (3) Be careful withNOLOCKall over the place. This is not a magical turbo button, and can lead to incorrect results in a variety of ways.ASsyntax was deprecated thanks. TheNOLOCKis required in our environment due to the high CRUD requests being hit and is in place per our DBA. I, personally, try to stay away from it but such is life.AS, it's the single quotes around aliases that's deprecated.SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTEDat the top, instead ofNOLOCKlittered throughout the query. At the very least, when your DBA learns about snapshot isolation, it's one change instead of<number of tables in query>.[like this].