while passing bigger date differnce getting erro in sql - sql-server

I have stored procedure like this on my DB:
ALTER procedure [dbo].[performance]
(#startdate nvarchar(100), #enddate nvarchar(100)
as begin
declare #date1 nvarchar(100) = convert(varchar, #startdate+' 00:00:00.000', 120)
declare #date2 nvarchar(100) = convert(varchar, #enddate+' 23:59:59.000', 120)
set NOCOUNT on;
select l.LocName,v.Vtype, SUM(DATEDIFF(MI,t.Paydate,t.DelDate)) as TotalDiff,
[dbo].[testfunction](
CONVERT(decimal(10,1), AVG( CONVERT(NUMERIC(18,2), DATEDIFF(SS,t.Paydate,t.DelDate) ) ))) as Average
from Transaction_tbl t
left join VType_tbl v
on t.vtid=v.vtid
left join Location_tbl l
on t.Locid=l.Locid
where t.Locid in
(select t1.Locid from Transaction_tbl t1)
and dtime between '' + #date1 +'' and ''+ #date2 +''
and Status =5
group by v.Vtype,l.LocName,l.Locid order by l.Locid
end
my testfunction ike this:
ALTER FUNCTION [dbo].[testfunction] (#dec NUMERIC(18, 2)) RETURNS Varchar(50)
AS
BEGIN
DECLARE
#hour integer,
#Mns integer,
#second decimal(18,3)
DECLARE #Average Varchar(50)
select #hour=CONVERT(int,#dec/60/60)
SELECT #Mns = convert(int, (#dec / 60) - (#hour * 60 ));
select #second=#dec % 60;
SELECT #Average =
convert(varchar(9), convert(int, #hour)) + ':' +
right('00' + convert(varchar(2), convert(int, #Mns)), 2) + ':' +
right('00' + CONVERT(decimal(10,0), convert(varchar(6), #second)), 6)
RETURN #Average
END
if i pass start date:2013-06-01 and end date:2013-08-01 then getting proper out put
if i pass start date:2010-06-01 and end date:2013-08-01 (bigger date difference) then getting error:
Arithmetic overflow error converting numeric to data type varchar.
i know having some problem with my function.but i am not able find out what is the issue with my function.if any one please help me to find out

try this .. i think your #Mns should be the problem
ALTER FUNCTION [dbo].[testfunction] (#dec NUMERIC(18, 2)) RETURNS Varchar(50)
AS
BEGIN
DECLARE
#hour decimal(18,2),
#Mns decimal(18,2),
#second decimal(18,3)
DECLARE #Average Varchar(50)
select #hour=CONVERT(int,#dec/60/60)
SELECT #Mns = convert(int, (#dec / 60) - (#hour * 60 ));
select #second=#dec % 60;
SELECT #Average =
convert(varchar(9), convert(int, #hour)) + ':' +
right('00' + convert(varchar(8), convert(decimal(18,2), #Mns)), 2) + ':' +
right('00' + CONVERT(decimal(10,0), convert(varchar(10), #second)), 6)
RETURN #Average
END

Related

Datetime is NULL when time format differs

I have specific time scenario which can be 4 digit, 6 digit or can be NULL or string as mentioned below. Here in scenario 3 & 4 my method of calculating datetime is not working and coming as NULL
Is there any way to get date with 00:00:00:000 as time for case 3 & 4?
& for 1 it should be 10:02:00:000
DECLARE #DATE VARCHAR(10) =CAST(GETDATE() AS DATE)
DECLARE #Time1 VARCHAR(10) = '1002'
DECLARE #Time2 VARCHAR(10) = '160634'
DECLARE #Time3 VARCHAR(10) = '0900XX'
DECLARE #Time4 VARCHAR(10) = ''
SELECT TRY_CONVERT(DATETIME, #DATE +' '
+LEFT(ltrim(#Time1), 2)
+ ':' + SUBSTRING(#Time1, 3, 2)
+ ':' + RIGHT(rtrim(#Time1), 2)) , TRY_CONVERT(TIME, #Time1), #Time1 AS Time
SELECT TRY_CONVERT(DATETIME, #DATE +' '
+LEFT(ltrim(#Time2), 2)
+ ':' + SUBSTRING(#Time2, 3, 2)
+ ':' + RIGHT(rtrim(#Time2), 2)) , TRY_CONVERT(TIME, #Time2), #Time2 AS Time
SELECT TRY_CONVERT(DATETIME, #DATE +' '
+LEFT(ltrim(#Time3), 2)
+ ':' + SUBSTRING(#Time3, 3, 2)
+ ':' + RIGHT(rtrim(#Time3), 2)) , TRY_CONVERT(TIME, #Time3), #Time3 AS Time
SELECT TRY_CONVERT(DATETIME, #DATE +' '
+LEFT(ltrim(#Time4), 2)
+ ':' + SUBSTRING(#Time4, 3, 2)
+ ':' + RIGHT(rtrim(#Time4), 2)) , TRY_CONVERT(TIME, #Time4), #Time4 AS Time
I would, personally, "pad out" the values to be 6 digits, inject the : characters, and then use TRY_CONVERT. Then you use ISNULL to return midmight for failed converions:
SELECT ISNULL(TRY_CONVERT(time(0),STUFF(STUFF(RIGHT('000000' + V.VarcharTime,6),5,0,':'),3,0,':')),'00:00:00')
FROM (VALUES(#Time1),
(#Time2),
(#Time3),
(#Time4))V(VarcharTime);
If 1002 is meant to be 10:02:00 rather than 00:10:02 then pad on the right, rather than the left:
SELECT ISNULL(TRY_CONVERT(time(0),STUFF(STUFF(LEFT(V.VarcharTime+'000000',6),5,0,':'),3,0,':')),'00:00:00')
FROM (VALUES(#Time1),
(#Time2),
(#Time3),
(#Time4))V(VarcharTime);
..................
DECLARE #Time4 VARCHAR(10) = ''
select #Time1 = concat(cast(#Time1 as varchar(8)), replicate('0', 8));
select #Time2 = concat(cast(#Time2 as varchar(8)), replicate('0', 8));
select #Time3 = concat(cast(#Time3 as varchar(8)), replicate('0', 8));
select #Time4 = concat(cast(#Time4 as varchar(8)), replicate('0', 8));
SELECT TRY_CONVERT(DATETIME, #DATE +' '......................

SQL Server Dynamic Pivot Query

I am creating a dynamic pivot query that shows the total NetAmount per Week of every Customers within a given date range. The problem is it doesn't ADD ALL the NetAmount within the Week. Here are the data of tblSampleSalesInvoices:
Here is my script.
CREATE PROCEDURE uspSalesWeeklySummary
(
#CustomerId INT,
#FromDate DATETIME,
#ToDate DATETIME
)
AS
SET NOCOUNT ON
DECLARE #Query AS VARCHAR(MAX)
DECLARE #DateStart DATETIME = #FromDate
DECLARE #tmp TABLE ([Date] VARCHAR(MAX))
DECLARE #Month VARCHAR(MAX)
DECLARE #Day VARCHAR(MAX)
DECLARE #ColumnHeader VARCHAR(MAX)
DECLARE #Headers VARCHAR(MAX)
WHILE DATEADD(WEEK, DATEDIFF(WEEK, '19050101', #DateStart), '19050101') <= DATEADD(WEEK, DATEDIFF(WEEK, '19050101', #ToDate), '19050101')
BEGIN
SET #month = DATENAME(Month, DATEADD(WEEK, DATEDIFF(WEEK, '19050101', #DateStart), '19050101'))
SET #day = CAST( DATEPART(DD, DATEADD(WEEK, DATEDIFF(WEEK, '19050101', #DateStart), '19050101')) AS VARCHAR(MAX) )
SET #ColumnHeader = 'Week ' + CAST(DatePart(WEEK,#DateStart) AS VARCHAR(MAX)) + ' - ' + CAST(Year(DATEADD(WEEK, DATEDIFF(WEEK, '19050101', #DateStart), '19050101')) AS VARCHAR(MAX)) + ' - ' + #month + ' - ' + #day
INSERT INTO #tmp ([Date])
VALUES (#ColumnHeader)
SET #DateStart = DATEADD(DD, 7, #DateStart)
END
SELECT #Headers = ISNULL(#Headers + ',','') + QUOTENAME(t.[Date])
FROM #tmp t
SET #Headers = #Headers + ',[Grand Total]'
SET #Query =
'
DECLARE #CustomerId INT = ' + CAST(#CustomerId AS VARCHAR) + '
DECLARE #FromDate DATETIME = CAST(''' + CAST(#FromDate AS VARCHAR) + ''' AS DATETIME)
DECLARE #ToDate DATETIME = CAST(''' + CAST(#ToDate AS VARCHAR) + ''' AS DATETIME)
DECLARE #Headers VARCHAR(MAX) = ''' + CAST(#Headers AS VARCHAR(MAX)) + '''
SELECT *
FROM
(
SELECT c.CustomerName AS CustomerName,
''Week '' + CAST(DatePart(WEEK,si.TransactionDate) AS VARCHAR(MAX)) + '' - ''
+ CAST(Year(DATEADD(WEEK, DATEDIFF(WEEK, ''19050101'', si.TransactionDate), ''19050101'')) AS VARCHAR(MAX)) + '' - ''
+ CAST(DATENAME(Month, DATEADD(WEEK, DATEDIFF(WEEK, ''19050101'', si.TransactionDate), ''19050101'')) AS VARCHAR(MAX)) + '' - ''
+ CAST(DATEPART(DD, DATEADD(WEEK, DATEDIFF(WEEK, ''19050101'', si.TransactionDate), ''19050101'')) AS VARCHAR(MAX)) AS Header,
SUM(si.NetAmount) AS NetAmount
FROM tblSampleSalesInvoices si
LEFT OUTER JOIN tblSampleCustomers c ON c.Id = si.CustomerId
WHERE (si.TransactionDate BETWEEN #FromDate AND DATEADD(WEEK, DATEDIFF(WEEK, ''19050101'', DATEADD(DD, 7 , #ToDate)), ''19050101''))
AND (si.CustomerId = #CustomerId OR #CustomerId = 0)
GROUP BY c.CustomerName, si.TransactionDate
UNION ALL
SELECT c.CustomerName AS CustomerName,
''Grand Total'' AS Header,
SUM(si.NetAmount) AS NetAmount
FROM tblSampleSalesInvoices si
LEFT OUTER JOIN tblSampleCustomers c ON c.Id = si.CustomerId
WHERE (si.TransactionDate BETWEEN #FromDate AND DATEADD(WEEK, DATEDIFF(WEEK, ''19050101'', DATEADD(DD, 7 , #ToDate)), ''19050101''))
AND (si.CustomerId = #CustomerId OR #CustomerId = 0)
GROUP BY c.CustomerName
) AS BaseData
PIVOT
(
SUM(NetAmount)
FOR Header IN (' + #Headers + ')
) AS Pivoting'
EXEC (#Query)
GO
EXEC uspSalesWeeklySummary 0,'01/01/2016','02/01/2016'
In this script the SUM of NetAmount will be 10000 only because From the Day of Jan 1, 2016 until Feb 1,2016 only 1 transaction (TR0002) has been made. But when I place Dec 27,2015 and Feb 1,2016 in the parameters. It shows only the NetAmount of TR0001 instead of 25000 which the SUM of TR0001 and TR0002.
If you are looking for week numbers relative to a start date and can create # tables then this might suit
CREATE PROCEDURE uspSalesWeeklySummary
(
#CustomerId INT,
#FromDate DATETIME,
#ToDate DATETIME
)
AS
SET NOCOUNT ON
set datefirst 1
/*
create table tblSampleSalesInvoices (id int,transactionNo int,customerid int,TransactionDate date,netamount int)
insert into tblSampleSalesInvoices values
(1,1,1,'2015-12-29',15000),
(2,2,1,'2016-01-01',15000),
(3,3,2,'2016-03-01',15000),
(4,4,3,'2016-04-01',15000),
(5,5,4,'2016-06-01',15000),
(6,6,1,'2016-09-01',15000),
(7,7,2,'2016-10-01',15000),
(8,8,3,'2016-12-01',15000),
(9,9,4,'2017-01-01',15000),
(10,10,1,'2017-04-01',15000),
(11,11,2,'2017-07-01',15000),
(12,12,3,'2017-10-01',15000),
(13,13,4,'2017-12-01',15000)
*/
--declare #CustomerId INT = 1
--declare #FromDate DATETIME = '2015-12-27'
--declare #ToDate DATETIME = '2016-02-01'
DECLARE #Query AS VARCHAR(MAX)
DECLARE #DateStart DATETIME = #FromDate
IF OBJECT_ID(N'tempdb..#Tempdates') IS NOT NULL
BEGIN
DROP TABLE #Tempdates
END
declare #id int = 0
create table #tempdates (id int,[lodate] date, [hidate] date ,yyyy varchar(4), mm varchar(max), dd int,txt varchar(max))
DECLARE #Month VARCHAR(MAX)
DECLARE #Day VARCHAR(MAX)
DECLARE #ColumnHeader VARCHAR(MAX)
DECLARE #Headers VARCHAR(MAX)
WHILE DATEADD(WEEK, DATEDIFF(WEEK, '19050101', #DateStart), '19050101') <= DATEADD(WEEK, DATEDIFF(WEEK, '19050101', #ToDate), '19050101')
BEGIN
set datefirst 1
SET #month = DATENAME(Month, DATEADD(WEEK, DATEDIFF(WEEK, '19050101', #DateStart), '19050101'))
SET #day = CAST( DATEPART(DD, DATEADD(WEEK, DATEDIFF(WEEK, '19050101', #DateStart), '19050101')) AS VARCHAR(MAX) )
SET #ColumnHeader = 'Week ' + CAST(DatePart(WEEK,#DateStart) AS VARCHAR(MAX)) + ' - ' +
CAST(Year(DATEADD(WEEK, DATEDIFF(WEEK, '19050101', #DateStart), '19050101')) AS VARCHAR(MAX)) + ' - ' + #month + ' - ' + #day
set #id = #id + 1
insert into #tempdates (id,[lodate],[hidate],yyyy,mm,dd,txt)
values (#id,#datestart,dateadd(dd,6,#datestart),
year(#datestart),
datename(month,#datestart),day(#datestart),
'Week ' + cast(#id as varchar(2)) + ' - ' + cast(datename(month,#datestart) as varchar(max)) + ' - ' + cast(day(#datestart) as varchar(max))
)
SET #DateStart = DATEADD(DD, 7, #DateStart)
END
update #tempdates
set hidate = #todate where id = #id
SELECT #Headers = ISNULL(#Headers + ',','') + QUOTENAME(t.[txt])
FROM #tempdates t
SET #Headers = #Headers + ',[Grand Total]'
--select #headers headers
--select * from #tempdates
set #query =
'
DECLARE #CustomerId INT = ' + CAST(#CustomerId AS VARCHAR) + '
DECLARE #FromDate DATETIME = CAST(''' + CAST(#FromDate AS VARCHAR) + ''' AS DATETIME)
DECLARE #ToDate DATETIME = CAST(''' + CAST(#ToDate AS VARCHAR) + ''' AS DATETIME)
DECLARE #Headers VARCHAR(MAX) = ''' + CAST(#Headers AS VARCHAR(MAX)) + '''
SELECT *
FROM
(
SELECT si.customerid,
t.txt as header,
SUM(si.NetAmount) AS NetAmount
FROM tblsamplesalesinvoices si
left join #tempdates t on si.Transactiondate between lodate and hidate
--LEFT OUTER JOIN tblSampleCustomers c ON c.Id = si.CustomerId
WHERE si.TransactionDate BETWEEN #FromDate AND DATEADD(WEEK, DATEDIFF(WEEK, ''19050101'', DATEADD(DD, 7 , #ToDate)), ''19050101'')
AND (si.CustomerId = #CustomerId OR #CustomerId = 0)
GROUP BY -- c.CustomerName,
si.customerid
,
t.txt
UNION ALL
SELECT si.CustomerId,
''Grand Total'' AS Header,
SUM(si.NetAmount) AS NetAmount
FROM tblsamplesalesinvoices si
-- LEFT OUTER JOIN tblSampleCustomers c ON c.Id = si.CustomerId
WHERE (si.TransactionDate BETWEEN #FromDate AND DATEADD(WEEK, DATEDIFF(WEEK, ''19050101'', DATEADD(DD, 7 , #ToDate)), ''19050101''))
AND (si.CustomerId = #CustomerId OR #CustomerId = 0)
GROUP BY si.customerid
) s
PIVOT
(
SUM(NetAmount)
FOR Header IN (' + #Headers + ')
) AS Pivoting'
--select #query
exec (#query)
IF OBJECT_ID(N'tempdb..#Tempdates') IS NOT NULL
BEGIN
DROP TABLE #Tempdates
END
go
Please note dates are UK localised

How to get Hour and minutes in decimal format from two dates

Here is my query
select DATEDIFF(minute, '2015-06-10 14:00:00.000', '2015-06-10 16:50:00.000') / 60.0
I get 2.833333 but i want 2.50
This gives you what you asked for, but please keep in mind that usually 2.50 is equal to 2.5 and means 5/2; you are using a notation that it is quite uncommon
DECLARE #f float
DECLARE #t nvarchar(15)
SELECT #f = DATEDIFF(hour, '2015-06-10 14:00:00.000', '2015-06-10 16:50:00.000')
SELECT #t = CONVERT(nvarchar(10), #f) + N'.' + CONVERT(nvarchar(10), (DATEDIFF(minute, '2015-06-10 14:00:00.000', '2015-06-10 16:50:00.000') - #f*60))
SELECT #t
So you want to show the hours and minutes? You could use this:
DECLARE #t1 datetime
SET #t1 = '2015-06-10 14:00:00.000'
DECLARE #t2 datetime
SET #t2 = '2015-06-10 16:50:00.000'
SELECT HHmm = CONVERT(varchar(3), DATEDIFF(minute, #t1, #t2) / 60)
+ '.'
+ RIGHT('0' + CONVERT(varchar(2), DATEDIFF(minute, #t1, #t2) % 60), 2)
Demo
The DateDiff function returns an integer. to display it as time you need to use some math and casting:
DECLARE #FromDate datetime = '2015-06-10 14:00:00.000',
#ToDate datetime = '2015-06-10 16:50:00.000'
select CAST(DATEDIFF(minute, #FromDate, #ToDate) / 60 as varchar) + ':' +
CAST(DATEDIFF(minute, #FromDate, #ToDate) % 60 as varchar)

Arithmetic overflow error converting numeric to data type while executing stored procedure

ALTER procedure [dbo].[performance]
#startdate nvarchar(100),
#enddate nvarchar(100)
as begin
set NOCOUNT on;
select l.LocName,
v.Vtype,
SUM(DATEDIFF(MI,t.Paydate,t.DelDate)) as TotalDiff,
[dbo].[testfunction](CONVERT(decimal(10,1), AVG(
CONVERT(NUMERIC(18,2), DATEDIFF(SS,t.Paydate,t.DelDate) ) ))) as Average
from
Transaction_tbl t
left join
VType_tbl v
on t.vtid=v.vtid
left join
Location_tbl l
on t.Locid=l.Locid
where
t.Locid in(select t1.Locid from Transaction_tbl t1) and
dtime between '' + #startdate +'' and ''+#enddate+'' and
Status =5
group by v.Vtype,l.LocName,l.Locid order by l.Locid
end
also i have one function like this:
ALTER FUNCTION [dbo].[testfunction] (#dec NUMERIC(18, 2)) RETURNS Varchar(50)
AS
BEGIN
DECLARE
#hour integer,
#Mns integer,
#second decimal(18,3)
DECLARE #Average Varchar(50)
select #hour=CONVERT(int,#dec/60/60)
SELECT #Mns = convert(int, (#dec / 60) - (#hour * 60 ));
select #second=#dec % 60;
SELECT #Average =
convert(varchar(9), convert(int, #hour)) + ':' +
right('00' + convert(varchar(2), convert(int, #Mns)), 2) + ':' +
right('00' + CONVERT(decimal(10,0), convert(varchar(6), #second)), 6)
RETURN #Average
END
am passing date like this:2013-01-01 and 2013-05-01
while executing this am getting error:Arithmetic overflow error converting numeric to data type varchar.
Try this one -
ALTER PROCEDURE [dbo].[performance]
#startdate NVARCHAR(100), --<-- try to use date datatype - DATE, DATETIME, ...
#enddate NVARCHAR(100)
AS
BEGIN
SET NOCOUNT ON;
SELECT
l.LocName
, v.Vtype
, SUM(DATEDIFF(MI, t.Paydate, t.DelDate)) AS TotalDiff
, [dbo].[testfunction](
CONVERT(DECIMAL(10, 1), AVG(CONVERT(NUMERIC(18, 2), DATEDIFF(SS, t.Paydate, t.DelDate))))
) AS Average
FROM dbo.Transaction_tbl t
LEFT JOIN dbo.VType_tbl v ON t.vtid = v.vtid
LEFT JOIN dbo.Location_tbl l ON t.Locid = l.Locid
WHERE dtime BETWEEN
CAST(#startdate AS DATETIME)
AND
CAST(#enddate AS DATETIME) --<-- possible problem
AND [status] = 5
--AND t.Locid IN (SELECT t1.Locid FROM Transaction_tbl t1) --<-- unnessesary
GROUP BY
v.Vtype
, l.LocName
, l.Locid
ORDER BY l.Locid
END
Update:
ALTER FUNCTION [dbo].[testfunction]
(
#dec NUMERIC(18, 2)
)
RETURNS Varchar(50)
AS BEGIN
DECLARE
#hour BIGINT
, #Mns BIGINT
, #second DECIMAL(18,3)
SELECT
#hour = CONVERT(BIGINT, #dec / 60 / 60)
, #Mns = CONVERT(BIGINT, (#dec / 60) - (#hour * 60))
, #second = #dec % 60
RETURN
CONVERT(VARCHAR(50), CONVERT(BIGINT, #hour)) + ':' + --<-- VARCHAR(9) => VARCHAR(50)
RIGHT('00' + CONVERT(VARCHAR(2), CONVERT(BIGINT, #Mns)), 2) + ':' +
RIGHT('00' + CONVERT(DECIMAL(2, 0), CONVERT(VARCHAR(6), #second)), 6)
END

Error in Customized Procedure "Must declare the scalar variable #startdate"

I have a procedure to fetch data as per the criteria passed. I works fine with #month, #year, #quater.
ALTER PROCEDURE dbo.SPReportTimeSpan
(
#Week int = null,
#Month int = null,
#Year int = null,
#Quater int = null
)
AS
SET NOCOUNT ON
DECLARE #sql nvarchar(4000)
If (#Week) IS NOT NULL
BEGIN
DECLARE #startdate Date, #enddate Date
EXEC dbo.SPReturnStartEndDateOfSpecifiedWeek #Week, #startdate OUTPUT, #enddate OUTPUT
SELECT #startdate, #enddate
END
SELECT #sql='SELECT
CRMDR.Id as Id,.
CRMDR.Request_For_Id as Request_For_Id
From [CRM].[dbo].[CRM_Doctor_Request] AS CRMDR
WHERE CRMDR.Is_Deleted=0 '
If (#Month) IS NOT NULL
SELECT #sql=#sql + ' AND MONTH(CRMDR.Date_Created) like (#Month) '
If (#Year) IS NOT NULL
SELECT #sql=#sql + ' AND YEAR(CRMDR.Date_Created) like (#Year) '
If (#Week) IS NOT NULL
SELECT #sql=#sql + ' AND (CRMDR.Date_Created) BETWEEN (#startdate) AND (#enddate) '
If (#Quater) IS NOT NULL
IF (#Quater = 1)
SELECT #sql=#sql + ' AND MONTH(CRMDR.Date_Created) in (4,5,6) '
IF (#Quater = 2)
SELECT #sql=#sql + ' AND MONTH(CRMDR.Date_Created) in (7,8,9) '
IF (#Quater = 3)
SELECT #sql=#sql + ' AND MONTH(CRMDR.Date_Created) in (10,11,12) '
IF (#Quater = 4)
SELECT #sql=#sql + ' AND MONTH(CRMDR.Date_Created) in (1,2,3) '
SELECT #sql=#sql + ' ORDER BY CRMDR.Id DESC '
EXEC sp_executesql #sql, N'#Month int, #Year int, #Quater int',
#Month, #Year, #Quater
RETURN
But for #week it gives error.
Running [dbo].[SPReportTimeSpan] ( #Week = 3, #Month = <NULL>, #Year = <NULL>, #Quater = <NULL> ).
Must declare the scalar variable "#startdate".
Column1 Column2
------------------------------ ------------------------------
2013-02-10 00:00:00.0000000 2013-02-17 00:00:00.0000000
No rows affected.
(1 row(s) returned)
#RETURN_VALUE = 0
Finished running [dbo].[SPReportTimeSpan].
I am not getting why its not working with week criteria. Please help if anyone have idea.
#startdate and #enddate are only accessible within the scope of your IF statement:
If (#Week) IS NOT NULL
BEGIN
DECLARE #startdate Date, #enddate Date
EXEC dbo.SPReturnStartEndDateOfSpecifiedWeek #Week, #startdate OUTPUT, #enddate OUTPUT
SELECT #startdate, #enddate
END
Move the declaration outside of the IF statement if you wish to reference these variables elsewhere:
DECLARE #startdate Date, #enddate Date
If (#Week) IS NOT NULL
BEGIN
EXEC dbo.SPReturnStartEndDateOfSpecifiedWeek #Week, #startdate OUTPUT, #enddate OUTPUT
SELECT #startdate, #enddate
END
FYI: The area where you make reference to these variables outside of the IF statement is here:
If (#Week) IS NOT NULL
SELECT #sql=#sql + ' AND (CRMDR.Date_Created) BETWEEN (#startdate) AND (#enddate) '
I got solution of my problem. To solve the problem, I need to explicitly cast datetime values to a character type so the query string can be concatenated as expected.
If (#Week) IS NOT NULL
SELECT #sql=#sql + ' AND (CRMDR.Date_Created) BETWEEN ''' + convert(VARCHAR,#startdate) + ''' AND ''' +convert(VARCHAR,#enddate) + ''''
or this (More Optimized)
SELECT #sql=#sql + ' AND (CRMDR.Date_Created BETWEEN #startdate AND #enddate)'
which needs to add something to sp_executesql
EXEC sp_executesql #sql, N'#Month int, #Year int, #Quater int, #Week int, #startdate datetime, #enddate datetime ',
#Month, #Year, #Quater, #Week, #startdate, #enddate
Your variables are out of scope.

Resources