Date Wise Report in SQL server 2008 - sql-server-2008

How to get following output ?
[1],[2],[3],[4],[5],[6],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17]
,[18],[19],[20]
,[21],[22],[23],[24],[25],[26],[27],[28],[29],[30]
Need to fetch all dates from given month in sql server
I want to display daily Date Wise report
Example :
If I pass date as '11/01/2012' then it should return above result
and if I pass December than 31 days.

Very unclear question but try
DECLARE #epoch DATETIME = '20130101'
;WITH cte AS
(
SELECT #epoch DateKey
UNION ALL
SELECT DATEADD(D, 1, DateKey)
FROM cte
WHERE MONTH(DATEADD(D, 1, DateKey))=MONTH(#epoch)
)
SELECT * FROM cte

try below code
declare #date datetime = '09/10/2012'
declare #noofdays int
select #noofdays =datediff(day, #date, dateadd(month, 1, #date))
DECLARE #startDate DATETIME=CAST(MONTH(#date) AS VARCHAR) + '/' + '01/' + + CAST(YEAR(#date) AS VARCHAR) -- mm/dd/yyyy
DECLARE #endDate DATETIME= CAST(MONTH(#date) AS VARCHAR) + '/' + cast(#noofdays as varchar) + '/' + CAST(YEAR(#date) AS VARCHAR)
;WITH Calender AS
(
SELECT #startDate AS CalanderDate
UNION ALL
SELECT CalanderDate + 1 FROM Calender
WHERE CalanderDate + 1 <= #endDate
)
SELECT [Date] = CONVERT(VARCHAR(10),CalanderDate,25)
FROM Calender
OPTION (MAXRECURSION 0)

I am able to find out answer my self....
Thanks Buddy for trying to help me...
DECLARE #COLSPIVOT AS NVARCHAR(MAX)=''
declare #MaxDate int
set #MaxDate=(SELECT day(DATEADD(ms,-2,DATEADD(MONTH, DATEDIFF(MONTH,0,'8/1/2013')+1,0)))
AS [Current Month])
declare #i int =1
while (#i<=#MaxDate)
begin
set #COLSPIVOT=#COLSPIVOT+'['+convert(varchar(10),#i)+']'
if(#i!=#MaxDate)
begin
set #COLSPIVOT=#COLSPIVOT+','
end
set #i=#i+1
end
select #COLSPIVOT

Related

Date Parameters Open Query SQL - ERROR: Unclosed quotation mark after the character string

Could someone look at my code below and let me know where I am going wrong. Trying to pass date parameters through Open Query & getting error - Unclosed quotation mark after the character string
--#PID varchar(11),
#START datetime,
#END datetime
AS BEGIN
SET NOCOUNT ON;
--DECLARE #PID1 varchar(11) = #PID
DECLARE #START1 datetime = #START
DECLARE #END1 datetime = #END
DECLARE #TSQL varchar(8000)
SET #TSQL = 'SELECT * FROM OPENQUERY ("CWSLIVE", ''SELECT * FROM pricing_base_data
WHERE date >= convert(date, ''''' + convert(varchar, #START1, 23)+ ''''', 23)
and date < convert(date, ''''' + convert(varchar, #END1, 23)+ ''''', 23))'
--PRINT (#TSQL)
EXEC (#TSQL)
END
GO
Use your query like this:- double quotes both side:
"SELECT * FROM OPENQUERY ("CWSLIVE", ''SELECT * FROM pricing_base_data
WHERE date >= convert(date, ''''' + convert(varchar, #START1, 23)+ ''''', 23) and date < convert(date, ''''' + convert(varchar, #END1, 23)+ ''''', 23))"

Convert or cast Datetime2 and varchar into datetime

I have a date stored as datetime2(7) and a time stored as varchar(5).
e.g.
Date = 2016-11-30 00:00:00.000000 (datetime2)
Time = 09:00 (varchar)
Output should be 2016-11-30 09:00:00.000000 (datetime).
How do I convert or cast these as a datetime. I have tried several ways but have been unsuccessful.
Thank you in advance for your help.
Maybe simple as this?
DECLARE #d DATETIME2(7)='2016-11-30 00:00:00.000000'
DECLARE #t VARCHAR(5)='09:00';
SELECT CAST(CAST(#d AS DATETIME) + CAST(#t+':00' AS DATETIME) AS datetime2(7))
Your time needs just :00 to it, than you can cast this to DATETIME. Two values of type DATETIMEcan be added.
The whole expression can be re-converted to DATETIME2.
How about something like this:
DECLARE #MYDATE DATETIME2;
DECLARE #MYTIME VARCHAR(5);
SET #MYDATE = '2016-11-30'; -- this is equal to 2016-11-30 00:00:00.000000
SET #MYTIME = '09:00';
-- for datetime2
SELECT CAST(CAST(LEFT(#MYDATE,10) AS VARCHAR) + ' ' + #MYTIME + ':00.000000' AS DATETIME2)
-- for datetime
SELECT CONVERT(DATETIME,CAST(LEFT(#MYDATE,10) AS VARCHAR) + ' ' + #MYTIME + ':00') -- for datetime

pulling variable in the select statement

I am trying to Pull #variable in select statement.
ex:
DECLARE #STARTDATE DATE
SELECT #STARTDATE = '8/1/2013'
DECLARE #ENDDATE DATE
SELECT #STARTDATE = '8/31/2013'
SELECT 'Results for DOS Serving' + #STARTDATE + 'to' + #EndDate
Any help please?
Thanks.
You can't just add string data and dates. You have to convert your dates to a string datatype first. (Also, in your code you never set #ENDDATE.
Something like this should get you close.
DECLARE #STARTDATE DATE
SELECT #STARTDATE = '8/1/2013'
DECLARE #ENDDATE DATE
SELECT #ENDDATE = '8/31/2013'
SELECT 'Results for DOS Serving ' + CONVERT(varchar, #STARTDATE, 110) + ' to ' + CONVERT(varchar, #EndDate, 110)
DECLARE #STARTDATE DATE
SET #STARTDATE = '8/1/2013'
DECLARE #ENDDATE DATE
SET #ENDDATE = '8/31/2013'
SELECT 'Results for DOS Serving ' + CONVERT(varchar(20), #STARTDATE, 110) + ' to ' + CONVERT(varchar(20), #EndDate, 110)

Getting dates between specific dates comma-separated

I have the following table:
CREATE TABLE dbo.Test
(
Name NVARCHAR(50)
,StartDate DATE
,EndDate DATE
)
INSERT INTO dbo.Test VALUES('ABC','28-Feb-14','03-Mar-14')
INSERT INTO dbo.Test VALUES('DEF','04-Mar-14','04-Mar-14')
Basically this contain start and end date of leave for a given user. I am expecting an output as shown below.
Expected output:
Name | WorkHour| LeaveHour | Remarks
-------------------------------------
ABC | 27 | 18 | 28-Feb, 03-Mar
DEF | 36 | 9 | 04-Mar
1 day of leave corresponds to 9 hours and a work week refers to Friday to the next Thursday. In this case that would be from 28-Feb to 06-Mar.
WorkHour refers to number of hours user has worked barring the leaves and not including the weekends.
LeaveHour refers to the number of hours user is on leave.
'Remarks' refers to distinct leaves for the user between StartDate and EndDate values that should appear as comma separated.
I am able to get the work hour (including weekends which is not desired), leave hour values but finding it difficult to have remarks and value excluding weekends
SELECT
RN.Name
,ISNULL(45 - ((DATEDIFF(DD, VT.StartDate, VT.EndDate) + 1) * 9 ), 0) AS 'WorkHours'
,ISNULL(((DATEDIFF(DD, VT.StartDate, VT.EndDate) + 1) * 9 ), 0) AS 'LeaveHours'
--distinct leave dates seperated by comma should be displayed as remarks
FROM
Test VT
LEFT JOIN
ResourceNames RN ON VT.UserId = RN.UserId
Can anyone help?
This should not be done in SQL, but here is a function that will do what you want:
create function CSVDates (#startDate datetime, #endDate datetime)
returns nvarchar(4000)
as
begin
declare #csv nvarchar(4000) = ''
declare #maxDays int = DATEDIFF(DD, #startDate, #endDate)
declare #count int = 0
declare #date datetime
while(#count <= #maxDays )
begin
if (DATENAME(dw, #date) = 'Saturday' OR DATENAME(dw, #date) = 'Sunday')
BEGIN
set #count = #count + 1
CONTINUE
END
set #date = DATEADD(d,#count, #startDate)
if (len(#csv) > 0) set #csv = #csv + ','
set #csv = #csv + DATENAME(day,#date) + '-' + DATENAME(month,#date)
set #count = #count + 1
end
return #csv
end
plug it into your select as CSVDates(vt.StartDate, vt.EndDate)
if you have a lot of dates in between, nvarchar(4000) may not be enough...
I figured out what was going wrong as finally I had time to work on this. Basically the block under weekend was not allowing date to get incremented which was resulting in the data not appearing.
Here is the working code for someone looking for similar ask
create function CSVDates (#startDate datetime, #endDate datetime)
returns nvarchar(4000)
as
begin
declare #csv nvarchar(4000) = ''
declare #maxDays int = DATEDIFF(DD, #startDate, #endDate)
declare #count int = 0
--assign start date
declare #date datetime = #startDate
while(#count <= #maxDays )
begin
if (DATENAME(dw, #date) = 'Saturday' OR DATENAME(dw, #date) = 'Sunday')
begin
--do nothing
set #count =#count
end
else
begin
if (len(#csv) > 0)
set #csv = #csv + ','
set #csv = #csv + DATENAME(day,#date) + '-' + SUBSTRING(DATENAME(month,#date),1,3)
end
set #count = #count + 1
set #date = DATEADD(d,#count, #startDate)
end
return #csv
end

Stripping the time out of datetime SQL Server 2005

I think I'm going crazy here.
I am trying to do a SP on SQL Server 2005 which takes a date, looks it up in another table and assigns a period number and week number (for financial calendar purposes).
The output needs to hold the date as a string, rather than datetime.
I simply CANNOT get the date to show without the time behind it.
I have tried a couple of methods:
select cast(floor(cast(#CalcDate as float)) as datetime)
I have made a function which converts it into a string and puts it back out again:
CREATE FUNCTION dbo.DateToVarchar (#DateIn datetime)
RETURNS varchar(10)
AS
BEGIN
declare #DD [varchar] (2)
declare #MM [varchar] (2)
declare #YYYY [varchar] (4)
declare #DateOut [varchar] (10)
declare #DDLen [int]
declare #MMLen [int]
set #DD = datepart(dd,#DateIn)
set #DDLen = len(#DD)
set #DD = (case when #DDLen < 2 then '0' + #DD else #DD end)
set #MM = datepart(mm,#DateIn)
set #MMLen = len(#MM)
set #MM = (case when #MMLen < 2 then '0' + #MM else #MM end)
set #YYYY = datepart(yyyy,#DateIn)
set #DateOut = #YYYY + '-' + #MM + '-' + #DD
return #DateOut
END
When I run the above function outside of the SP I get the date back just fine. When I run it through the SP it comes back as 2012-12-30 00:00:00.000
The variable #CalcDate is declared as a varchar(10)
Any ideas?
Thanks in advance
EDIT
Here is the body of the SP so far:
declare #StartDate [datetime]
, #EndDate [Datetime]
, #CalcDate [datetime] --This number will change in the WHILE loop to reflect the increment of days
, #Week [varchar]
, #Period [varchar]
, #i [int]
, #Year [int]
, #CalcDay [int]
, #CalcMonth [int]
, #CalcYear [int]
, #ConcatDate [char] (10)
set #StartDate = '2012-12-30'
set #EndDate = '2013-01-28'
set #Year = 2013
set #i = -1
-- Going to do a while loop here and instead of Week number and Period Number I'm going to do some calculations
set #Week = (Select WeekNum from aaGreensPeriodListTest Where PeriodNum = 1 and WeekNum = 1)
set #Period = (Select PeriodNum from aaGreensPeriodListTest Where PeriodNum = 1 and WeekNum = 1)
set #CalcDate = #StartDate + #i
set #CalcMonth = datepart(mm,#calcdate)
insert into aaGreensPeriodTest(RealDate,GreensYear,GreensPeriod,GreensWeek)
values (#CalcDate,#Year,#Period,#Week)
select #CalcDate as CalcDate, #CalcMonth as CalcMonth
SQL Server 2005 does not support date type without time part.
If your need to get date as a string you can use convert function. For example:
declare #date datetime;
set #date = getdate();
select convert(varchar, #date, 101) -- that will return date in ‘mm/dd/yyyy’ format
If you need a datetime variable without time part for some calculations, you can use an expression below:
declare #date datetime;
set #date = getdate();
select dateadd(dd, datediff(dd, 0, #date), 0)
As per http://msdn.microsoft.com/en-ca/library/ms187928.aspx, you cannot cast float->date directly. It's simply not supporte. But you can cast a datetime->date, so you'll have to double-cast. Or given your example, triple-cast:
CAST(CAST(CAST(#CalcDate AS float) AS datetime) AS date)