Good Morning All,
I’m trying to refactor an SQL stored procedure. I’m no SQL expert, but something tells me there must be a better way to do this.
IF @ipv_dtEndDate IS NOT NULL
BEGIN
SET @ipv_dtEndDate = DATEADD(hh,23,@ipv_dtEndDate)
SET @ipv_dtEndDate = DATEADD(mi,59,@ipv_dtEndDate)
SET @ipv_dtEndDate = DATEADD(ss,59,@ipv_dtEndDate)
END
This value is used later inside a WHERE clause. These filters seem difficult to understand to me. I was hoping to come up with a cleaner implementation.
AND qtrh.StatusTime <= IsNull(@ipv_dtEndDate, qtrh.StatusTime)
And this date calculation…
AND DATEDIFF(ss,qtrh.StatusTime,ISNULL(@dtNow,DATEADD(ss,-1,qtrh.StatusTime))) < DATEDIFF(ss,ISNULL(@dtDateOptionCompare,GETDATE()),GETDATE())
… seems quite convoluted and unreadable. If any SQL gurus out there have some suggestions on how I can improve this, I would love to hear some ideas. Thanks for your time. Have a terrific holiday weekend.
Cheers,
~ck in San Diego
If the only use of
@ipv_dtEndDateis inside the Where clause, you could remove the entireIF @ipv_dtEndDate IS NOT NULLblock, and replace the condition in the SQL query with:(Strictly speaking, you will now also be including StatusTime values between 23:59:59 and 00:00:00, which were previously excluded.)