Compare datetime value in stored procedure
I am having trouble writing SQL Server queries / procedures with format DateTime
in tables.
My application is running on a standard ASP.NET MVC4 stack with SQL Server.
My table Bookings
has the following structure:
CREATE TABLE [dbo].[Bookings]
(
[BookingId] INT IDENTITY (1, 1) NOT NULL,
[ShowId] INT NOT NULL,
[RowId] INT NULL,
[Username] VARCHAR(100) NULL,
[PaymentId] INT NULL,
[ShowDate] DATETIME NULL,
.....
....
);
I wrote two stored procedures where I am trying to compare a table column ShowDate
with different date parameters declared in a stored procedure.
Procedure # 1:
CREATE PROCEDURE [dbo].[GetBookingsByDate]
@venueid int,
@fromdate datetime,
@todate datetime
AS
BEGIN
SELECT
City, Title, ScreenTitle, ShowDate,
SUM([Qty]) AS Quantity,
SUM([Charges]) AS TotalAmount,
SUM([OtherCharges]) AS OtherCharges
FROM
ShowBookings
WHERE
Venueid = @venueid
AND ShowDate BETWEEN @fromdate AND @todate
GROUP BY
ScreenId, ShowDate, Venueid, Title, ScreenTitle, City
END
Procedure number 2:
CREATE PROCEDURE [dbo].[GetAudienceReportsHistory]
@state varchar,
@city varchar,
@theaterName varchar,
@showdate datetime
AS
BEGIN
SELECT
b.BookingId, b.MobileNo, b.SeatNumbers, b.EmailId,
sc.ScreenTitle, sh.ShowTime, a.Title,
b.Username, b.SMSStatus
FROM
Bookings b
JOIN
Shows sh ON b.ShowId = sh.Id
JOIN
Venues AS v ON sh.Venue_Id = v.Id
JOIN
Artifacts a ON sh.Artifact_Id = a.Id
JOIN
Screens AS sc ON sh.Screen_ScreenId = sc.ScreenId
WHERE
b.ShowDate = @showdate
AND b.IsBooked = 'true'
AND b.TimeSolt = '0'
AND v.Title = @theaterName
AND v.City = @city
END
As you can see, procedure # 1 takes two parameters, datetime, fromdate
and todate
. The second procedure takes only one datetime parameter ShowDate
.
Procedure # 1 returns the correct result set, but Procedure # 2 returns no results at all. But I have cross-checked in the tables that I have the correct data to be returned for the Proc2 query. Seems like a DateTime format mismatch.
I am sending datetime parameters to requests in "yyyy-mm-dd" format (ex: 2017-05-30). Inside the table, the column ShowDate
is stored in the "dd-mm-yyyy" format (for example, 05/30/2017).
I tried to send the parameter in different date formats, but I am not getting any results for Proc2. Please help me to solve this. Thank you in advance. Let me know if you need more information.
source to share
you should note that datetime includes time, so when you equate this to a datetime field it will never be equal due to the time difference ... what you can do is specify both dates ... meanwhile between capture time within date
cast(showdate as date) = cast(@showdate as date)
or DateDIFF
datediff(day,@showdate,showdate) = 0
source to share