Compare datetime value in stored procedure - sql

I am having trouble writing SQL Server queries/procedures with DateTime format in the tables.
My application runs on a standard ASP.NET MVC4 stack with SQL Server.
My table Bookings has this 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 have written two stored procedures where I am trying to compare table column ShowDate with different date parameters declared in 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 #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 datetime parameters, fromdate and todate. The second procedure takes only one datetime parameter showdate.
Procedure #1 returns the correct set of results, however procedure #2 returns no results at all. But I have crosschecked in the tables that I have proper data which should be returned for the Proc2 query. There seems to be some DateTime format mismatch.
I'm sending datetime parameters to the queries in "yyyy-mm-dd" format (eg: 2017-05-30). Inside the table the ShowDate column is stored in "dd-mm-yyyy" (eg: 30-05-2017) format.
I have tried sending the parameter in different date formats but I'm not getting any results for Proc2. Kindly help me in solving this. Thanks in advance. Let me know if you need more info.

you have to note that datetime includes time so when you equate that to a datetime field it will never be equal due to time difference... what you can do is cast both dates... meanwhile between captures time within the date
cast(showdate as date) = cast(#showdate as date)
or DateDIFF
datediff(day,#showdate,showdate) = 0

You Need to convert Date Proper Formate like this
CONVERT(date, b.ShowDate) = CONVERT(date,#showdate )

Related

Call tabled function with parameters in sql

I'm a newbie in SQL and with programming languages in general. I'm trying to make a tabled function in SQL (SQL Server):
CREATE FUNCTION dbo.fn_Get_List (
#PAR_user_code INT
, #PAR_id_session INT
, #PAR_id_profile INT
, #PAR_days_check_from DATETIME
, #PAR_days_check_to DATETIME
, #PAR_register BIT
)
RETURNS #tb_return table(
num_prat int,
num_ipotec int,
typeipotec tinyint,
fee money,
stipulated_date smalldatetime,
expire_date smalldatetime,
renew_date datetime,
delete_date date,
authentication_date date,
prime money)
AS
BEGIN
and then I have to call it in another sql page. I've tried to use this syntax:
DECLARE #PAR_user_code INT
DECLARE #PAR_id_session INT
DECLARE #PAR_id_profile INT
DECLARE #PAR_days_check_from DATETIME
DECLARE #PAR_days_check_to DATETIME
DECLARE #PAR_register BIT
SELECT *
FROM fn_IPO_Get_Elenco_Ipoteche(#PAR_user_code,#PAR_id_session,#PAR_id_profile,#PAR_days_check_from,#PAR_days_check_to,#PAR_register)
If I run my SELECT I don't have any result, because my parameters are not initialized.
How can I insert values into them? What I want to do is take values from a table that I've created and where I have these attributes and when I run my webpage I'll fill them.
For example, if I log with ID Session = 1, I'd like to see it into #PAR_id_session and then valorise the other parameters with the user's choices on the webpage (I have multiple choice for #PAR_days_check_from). How can I do it if I don't know the values?
Intialization of variable in T-SQL:
DECLARE #PAR_user_code INT = 1;
or by using SET:
SET #PAR_user_code = 1;
The function arguments can be populated from table using CROSS/OUTER APPLY:
SELECT *
FROM my_table t
CROSS APPLY fn_IPO_Get_Elenco_Ipoteche(t.user_code, ...) f
WHERE t.col = ? -- any condition

writing from a SQL view to a Table

Hello I've got this SQL View (Namely Login_Monitor) that I've created using a number of table joins
What I'm wanting to do now is to use a few columns in this View to write to a seperate table that I've created.
But Im gettiing Null values written to table instead of actual data.
This is how I created my destination table
create table MS_Login_Monitor
(date date,
time time,
USERID char(15),
COMPANY_NAME char(65),
LOGIN_DATE_TIME datetime,
TIME_SINCE_LAST_ACTION int,
)
This is the query I used to write view data to destination table
declare #date date
declare #time time
declare #USERID char(20)
declare #COMPANY_NAME char(65)
declare #LOGIN_DATE_TIME datetime
declare #TIME_SINCE_LAST_ACTION nchar(7)
set #date = CURRENT_TIMESTAMP
set #time = CURRENT_TIMESTAMP
select * from Login_Monitor
INSERT INTO DYNAMICS..MS_Login_Monitor (date, time,USERID, COMPANY_NAME, LOGIN_DATE_TIME, TIME_SINCE_LAST_ACTION)
VALUES (#date, #time,#USERID,#COMPANY_NAME, #LOGIN_DATE_TIME, #TIME_SINCE_LAST_ACTION)
could someone explain please why I get NULL values written to table please or if there are errors in my SQL query.
Thanks
You can try something like this;
INSERT INTO DYNAMICS..MS_Login_Monitor (date, time,USERID, COMPANY_NAME, LOGIN_DATE_TIME, TIME_SINCE_LAST_ACTION)
select #date, #time, X, Y.....(use actual column names of view) from Login_Monitor
You dont need other parameters.

Construct Dynamic Complex Where Clause in Stored Procedure

I need to write a stored procedure that uses different where-clauses based on given input parameters. Specifically I need evaluate two date-time parameters, and based on these parameters, I need to construct different where-clauses. So far I am having problems making it work.
The stored procedures takes start-date and end-date parameters as given by users, and use these two parameters to find records that have their start-date and end-date overlapping these user-input parameters.
Below is the pseudo-code of the stored procedure I want to create:
CREATE PROCEDURE sp_MyReport #organisation nvarchar(255) = NULL, #start_date nvarchar(255) = NULL, #end_date nvarchar(255) = NULL
AS
DECLARE #dateTimeOverlapWhereClause nvarchar(1000)
-- Construct the appropriate where-condition based on the user input
if #start_date is not null and #end_date is not null
#dateTimeOverlapWhereClause = (cast(start_date as datetime) <= prj.PlanEnd) and (cast(end_date as datetime) >= prj.PlanStart)
else if #start_date is not null and #end_date is null
#dateTimeOverlapWhereClause = (prj.PlanStart >= cast(#start_date as datetime))
else if #start_date is null and #end_date is not null
#dateTimeOverlapWhereClause = (prj.PlanEnd <= cast(#end_date as datetime))
else -- both input dates are null so we use open-ended dates instead
#dateTimeOverlapWhereClause = ((cast('1900-01-01' as datetime) <= prj.PlanEnd) and (cast('9999-12-31' as datetime) >= prj.PlanStart))
-- This is the query that need to use the dynamic where condition
select
prj.SrcGISID,
prj.PlanStart,
prj.PlanEnd,
prj.WorksClass,
prj.Description,
prj.JobStatus,
prj.Stage
from PROJECT prj
inner join ORGANISATION org on prj.OrgID = org.ID and org.OrganisationName = #organisation
and #dateTimeOverlapWhereClause
go
How do I make the #dateTimeOverlapWhereClause dynamically constructed? I have done some research but most of the answers are based on simple variables. SQL-injection is not so much a concern here as this stored procedure is used internally by organisation. I am using MS SQL Server 2012.
Thanks in advance.

How do I properly SELECT WHERE Effective_Date >= 'Given_Date' in a stored procedure?

I have this select statement that returns the results I'm looking for:
SELECT *
FROM Database.dbo.Table
WHERE Effective_Date >= '04/01/2014'
AND Chain = 'MCD'
I'm looking to turn this into a stored procedure with the following variables, #EffectiveDate and #Chain so that I can simply replace the date and chain to get different results. Here is the stored procedure I've made that doesn't work correctly:
CREATE PROCEDURE Database.dbo.StoredProc
#Chain VARCHAR(255),
#EffectiveDate VARCHAR(255)
AS
SELECT *
FROM Database.dbo.Table
WHERE Effective_Date >= '+#EffectiveDate+'
AND Chain = '+#Chain+'
GO
I'd like to execute this stored procedure like this:
EXEC Database.dbo.StoredProc
#PharmacyChain = N'MCD',
#EffectiveDate = N'04/01/2014'
;
GO
In this example, Table.Effective_Date is in datetime format. When I run the SELECT statement w/o the stored proc, the date comparison works fine to only select records with effective date after '04/01/2014'. However, when it's run using the variables int he stored proc, it doesn't convert the date correctly to compare. I've tried changing the EffectiveDate variable to datetime format, but still had no luck. Any help would be greatly appreciated. Thank you
Parameters should match the column datatype
#Chain VARCHAR(255) -- what is Chain?
#EffectiveDate datetime -- or date etc
And simply do this
SELECT *
FROM dbo.Table
WHERE Effective_Date >= #EffectiveDate
AND Chain = #Chain;
You don't need 3 part object names either

How to pass multiple values to single parameter in stored procedure

I'm using SSRS for reporting and executing a stored procedure to generate the data for my reports
DECLARE #return_value int
EXEC #return_value = [dbo].[MYREPORT]
#ComparePeriod = 'Daily',
#OverrideCompareDate = NULL,
#PortfolioId = '5,6',
#OverrideStartDate = NULL,
#NewPositionsOnly = NULL,
#SourceID = 13
SELECT 'Return Value' = #return_value
GO
In the above when I passed #PortfolioId = '5,6' it is giving me wrong inputs
I need all records for portfolio id 5 and 6 also is this correct way to send the multiple values ?
When I execute my reports only giving #PortfolioId = '5' it is giving me 120 records
and when I execute it by giving #PortfolioId = '6' it is giving me 70 records
So when I will give #PortfolioId = '5,6' it should have to give me only 190 records altogether, but it is giving me more no of records I don't understand where I exactly go wrong .
Could anyone help me?
thanks
all code is too huge to paste , i'm pasting relevant code please suggest clue.
CREATE PROCEDURE [dbo].[GENERATE_REPORT]
(
#ComparePeriod VARCHAR(10),
#OverrideCompareDate DATETIME,
#PortfolioId VARCHAR(50) = '2', --this must be multiple
#OverrideStartDate DATETIME = NULL,
#NewPositionsOnly BIT = 0,
#SourceID INT = NULL
) AS
BEGIN
SELECT
Position.Date,
Position.SecurityId,
Position.Level1Industry,
Position.MoodyFacilityRating,
Position.SPFacilityRating,
Position.CompositeFacilityRating,
Position.SecurityType,
Position.FacilityType,
Position.Position
FROM
Fireball_Reporting.dbo.Reporting_DailyNAV_Pricing POSITION WITH (NOLOCK, READUNCOMMITTED)
LEFT JOIN Fireball.dbo.AdditionalSecurityPrice ClosingPrice WITH (NOLOCK, READUNCOMMITTED) ON
ClosingPrice.SecurityID = Position.PricingSecurityID AND
ClosingPrice.Date = Position.Date AND
ClosingPrice.SecurityPriceSourceID = #SourceID AND
ClosingPrice.PortfolioID IN (
SELECT
PARAM
FROM
Fireball_Reporting.dbo.ParseMultiValuedParameter(#PortfolioId, ',') )
This can not be done easily. There's no way to make an NVARCHAR parameter take "more than one value". What I've done before is - as you do already - make the parameter value like a list with comma-separated values. Then, split this string up into its parts in the stored procedure.
Splitting up can be done using string functions. Add every part to a temporary table. Pseudo-code for this could be:
CREATE TABLE #TempTable (ID INT)
WHILE LEN(#PortfolioID) > 0
BEGIN
IF NOT <#PortfolioID contains Comma>
BEGIN
INSERT INTO #TempTable VALUES CAST(#PortfolioID as INT)
SET #PortfolioID = ''
END ELSE
BEGIN
INSERT INTO #Temptable VALUES CAST(<Part until next comma> AS INT)
SET #PortfolioID = <Everything after the next comma>
END
END
Then, change your condition to
WHERE PortfolioId IN (SELECT ID FROM #TempTable)
EDIT
You may be interested in the documentation for multi value parameters in SSRS, which states:
You can define a multivalue parameter for any report parameter that
you create. However, if you want to pass multiple parameter values
back to a data source by using the query, the following requirements
must be satisfied:
The data source must be SQL Server, Oracle, Analysis Services, SAP BI
NetWeaver, or Hyperion Essbase.
The data source cannot be a stored procedure. Reporting Services does
not support passing a multivalue parameter array to a stored
procedure.
The query must use an IN clause to specify the parameter.
This I found here.
I spent time finding a proper way. This may be useful for others.
Create a UDF and refer in the query -
http://www.geekzilla.co.uk/view5C09B52C-4600-4B66-9DD7-DCE840D64CBD.htm
USE THIS
I have had this exact issue for almost 2 weeks, extremely frustrating but I FINALLY found this site and it was a clear walk-through of what to do.
http://blog.summitcloud.com/2010/01/multivalue-parameters-with-stored-procedures-in-ssrs-sql/
I hope this helps people because it was exactly what I was looking for
Either use a User Defined Table
Or you can use CSV by defining your own CSV function as per This Post.
I'd probably recommend the second method, as your stored proc is already written in the correct format and you'll find it handy later on if you need to do this down the road.
Cheers!
I think, below procedure help you to what you are looking for.
CREATE PROCEDURE [dbo].[FindEmployeeRecord]
#EmployeeID nvarchar(Max)
AS
BEGIN
DECLARE #sqLQuery VARCHAR(MAX)
Declare #AnswersTempTable Table
(
EmpId int,
EmployeeName nvarchar (250),
EmployeeAddress nvarchar (250),
PostalCode nvarchar (50),
TelephoneNo nvarchar (50),
Email nvarchar (250),
status nvarchar (50),
Sex nvarchar (50)
)
Set #sqlQuery =
'select e.EmpId,e.EmployeeName,e.Email,e.Sex,ed.EmployeeAddress,ed.PostalCode,ed.TelephoneNo,ed.status
from Employee e
join EmployeeDetail ed on e.Empid = ed.iEmpID
where Convert(nvarchar(Max),e.EmpId) in ('+#EmployeeId+')
order by EmpId'
Insert into #AnswersTempTable
exec (#sqlQuery)
select * from #AnswersTempTable
END