Comparing DateTIme Column value with DateTime String SQL Server - sql-server

I am trying to compare DateTime string to a DateTime Value Column in DB but its returning me 0 records Here is the query
DECLARE #p_date DATETIME
SET #p_date= CONVERT( DATETIME, '9/1/2015 10:06:22 PM', 131 )
SELECT UpdateUserId, UpdateTimeA
From SubmitSheets
WHERE CONVERT( DATETIME, UpdateTimeA, 131 ) = #p_date
the value in UpdateTimeA column is 2015-09-01 22:06:22.447

Like I said in my comment, I'm not sure 131 is the right style to convert to datetime (at least, I get a very different value).
If you want to compare dates without the second fraction, you'll have to compare as strings. Converting both dates to a varchar(19) will cut off the fractions.

Finally found a way
SELECT UpdateUserId,UpdateTimeA
From SubmitSheets
WHERE CONVERT(VARCHAR(16),UpdateTimeA,100) = CONVERT(VARCHAR(16),CONVERT( DATETIME, '9/1/2015 10:06:22 PM',101),100)

I think the #p_date parameter is not in same format. Try this:
DECLARE #p_date DATETIME
SET #p_date= CONVERT( DATETIME, '9/1/2015 10:06:22 PM')
SELECT UpdateUserId, UpdateTimeA
From SubmitSheets
WHERE CONVERT(DATETIME, (CONVERT(VARCHAR, UpdateTimeA, 101) + ' ' + CONVERT(VARCHAR, UpdateTimeA, 108)), 131) = CONVERT(DATETIME, #p_date, 131)
So another tryout may be
An example:
DECLARE #a TABLE
(
ID int,
datet datetime
)
INSERT INTO #a
(ID, datet)
VALUES (1 , CONVERT(DATETIME, GETDATE(), 131))
,(2 , CONVERT(DATETIME, GETDATE(), 131))
,(3 , CONVERT(DATETIME, GETDATE(), 131))
,(4 , CONVERT(DATETIME, GETDATE(), 131))
,(5 , CONVERT(DATETIME, GETDATE(), 131))
,(6 , CONVERT(DATETIME, GETDATE(), 131))
,(7 , CONVERT(DATETIME, GETDATE(), 131))
,(8 , CONVERT(DATETIME, GETDATE(), 131))
,(9 , CONVERT(DATETIME, GETDATE(), 131))
SELECT ID, datet, ConvDatetime
FROM
(
SELECT ID, datet
,CONVERT(DATETIME, (CONVERT(VARCHAR, datet, 101)
+ ' '
+ CONVERT(VARCHAR, datet, 108)), 131) AS ConvDatetime
FROM
#a
) AS dt
WHERE
dt.ConvDatetime= CONVERT(DATETIME,
(CONVERT(VARCHAR, GETDATE(), 101)
+ ' '
+ CONVERT(VARCHAR, GETDATE(), 108))
, 131) -- CONVERT( DATETIME, '9/1/2015 10:06:22 PM', 131 )

Related

HOW TO CREATE TEMP TABLE USING stored procedure

I want to create a stored procedure in SQL Server 2012 that returns a temp table.
My code is
CREATE PROC [dbo].[aac_trial_balance_data]
#company_code char(5),
#target_level int,
#StartDate char(12),
#EndDate char(12)
AS
BEGIN
SELECT
dbo.getParentCode(chart_code,#target_level,LEVEL) chart_code,
level,
SUM(debit) debit,
SUM(credit) credit
FROM
acc_trial_balance_vw
WHERE
convert(datetime, create_date, 103) between convert(datetime, cast(#StartDate as datetime), 103)
and convert(datetime, cast(#EndDate as datetime) + '23:59:59', 103)
AND company_code = #company_code
GROUP BY
chart_code, LEVEL
END
I want to create a Temp table after the query like
CREATE PROC [dbo].[aac_trial_balance_data]
#company_code char(5),
#target_level int,
#StartDate char(12),
#EndDate char(12)
AS
BEGIN
(select
dbo.getParentCode(chart_code,#target_level,LEVEL) chart_code,
level,
SUM(debit) debit,
SUM(credit) credit
from acc_trial_balance_vw
where
convert(datetime,create_date,103) between convert(datetime, cast(#StartDate as datetime) , 103)
and convert(datetime, cast(#EndDate as datetime)+'23:59:59' , 103)
and company_code = #company_code
GROUP BY chart_code, LEVEL
)
AS
#TEMP-TABLE -- This is my Temp Table That i want to create
END
How can id do it
you can create temp table, just use
If Object_Id('Tempdb..#temp') Is Not Null
Drop Table #temp1
create table #temp(your columns)
Insert into #temp select...
or use select into #temp like
select
dbo.getParentCode(chart_code,#target_level,LEVEL) chart_code,
level,
SUM(debit) debit,
SUM(credit) credit into #tempTable
from acc_trial_balance_vw
where
convert(datetime,create_date,103) between convert(datetime, cast(#StartDate as datetime) , 103)
and convert(datetime, cast(#EndDate as datetime)+'23:59:59' , 103)
and company_code = #company_code
GROUP BY chart_code, LEVEL
try this:
(select
dbo.getParentCode(chart_code,#target_level,LEVEL) chart_code,
level,
SUM(debit) debit,
SUM(credit) credit
INTO #THIS_TEMP_TABLE
from acc_trial_balance_vw
where
convert(datetime,create_date,103) between convert(datetime, cast(#StartDate as datetime) , 103)
and convert(datetime, cast(#EndDate as datetime)+'23:59:59' , 103)
and company_code = #company_code
GROUP BY chart_code, LEVEL)
SELECT * FROM #THIS_TEMP_TABLE
Drop table #THIS_TEMP_TABLE
Try inserting into #temptable after your dbname from acc_trial_balance_vw
CREATE PROC [dbo].[aac_trial_balance_data]
#company_code char(5),
#target_level int,
#StartDate char(12),
#EndDate char(12)
AS
BEGIN
(select
dbo.getParentCode(chart_code,#target_level,LEVEL) chart_code,
level,
SUM(debit) debit,
SUM(credit) credit
into #TEMPTABLE -->>> Inserting here
from acc_trial_balance_vw
where
convert(datetime,create_date,103) between convert(datetime, cast(#StartDate as datetime) , 103)
and convert(datetime, cast(#EndDate as datetime)+'23:59:59' , 103)
and company_code = #company_code
GROUP BY chart_code, LEVEL
)
AS
END
create table #temp(company_code char(5),target_level int,StartDate char(12))
insert into #temp('','','')
select * from #temp
select
dbo.getParentCode(chart_code,#target_level,LEVEL) chart_code,
level,
SUM(debit) debit,
SUM(credit) credit
from acc_trial_balance_vw
where
convert(datetime,create_date,103) between convert(datetime, cast(#StartDate as datetime) , 103)
and convert(datetime, cast(#EndDate as datetime)+'23:59:59' , 103)
and company_code = #company_code
GROUP BY chart_code, LEVEL

Convert nvarchar to datetime sql server

I try to convert 2016/07/15 (nvarchar format) to this datetime format 2016-07-15 00:00:00 in sql server. But i need the time part to be the current time. can any one help ?
This is my sp:
declare #DateTime varchar(50)
set #DateTime = '2016/07/15'
select convert(varchar, cast(#DateTime as datetime), 120)
You can use this:
declare #DateTime varchar(50)
set #DateTime = CONCAT('2016/07/15' , ' ', CONVERT(TIME, GETDATE()))
select #DateTime
select convert(varchar, cast(#DateTime as datetime2(7)), 120)
Or replace the CONCAT with:
set #DateTime = '2016/07/15' + ' ' + CONVERT(NVARCHAR(50), CONVERT(TIME, GETDATE()))
Try this...
Just concat time with your output
declare #DateTime varchar(50)
set #DateTime = '2016/07/15'
select convert(varchar, cast(#DateTime as datetime), 101) + ' ' + CONVERT(varchar, getdate(),108)
Try like this,
DECLARE #DateTime VARCHAR(50)
SET #DateTime = '2016/07/15'
SELECT DATEADD(day, 0, DATEDIFF(day, 0, #DateTime)) + DATEADD(day, 0 - DATEDIFF(day, 0, getdate()), getdate())

Convert int MMDDYYYY into datetime MM-DD-YYYY

I would like to
convert int MMDDYYYY (e.g.-5112012) into datetime MM-DD-YYYY
and then convert datetime MM-DD-YYYY into YYYY-MM-DD
or if the above can be done in one step converting int MMDDYYYY into datetime YYYY-MM-DD?
For reference, earlier I converted int YYYYMMDD into datetime YYYY-MM-DD using the following syntax:
declare #date int;
set #date = 19900511
select CONVERT(datetime, convert(varchar(8),#date), 103)
DECLARE #date INT;
SET #date = 5112012
SELECT CONVERT(DATETIME, LEFT('0' + CONVERT(VARCHAR(8), #date), 2) + '-' + SUBSTRING( '0' + CONVERT(VARCHAR(8), #date), 3, 2) + '-' + RIGHT(#date,4))
That bails the water, now fix the leak; change the storage from int to a proper date or datetime :)
declare #date int
set #date = 19900511
select CONVERT(CHAR(10), CONVERT(datetime, convert(varchar(8),#date), 103), 21)
SQL Fiddle
The result is 1990-05-11
convert( datetime,
case when #MMDDYYYY = 0 then
null
else
substring(convert( varchar(9), 800000000 + #MMDDYYYY ) , 2, 2)
+ '/' + substring(
convert( varchar(9), 800000000 + #MMDDYYYY ) , 4, 2)
+ '/' + right(#MMDDYYYY,4) end ) as New_Date

Getting Error when converting to datetime :Date Column + Time Column

Below is my sql query, Inner query returning the value but outer query returning error:
"Conversion failed when converting character string to smalldatetime data type. "
SELECT x.*
FROM (
SELECT
Convert(SMALLDATETIME, Convert(VARCHAR(30), Convert(DATE, Event_Date, 101)) +
Convert(VARCHAR(30), ' ') + Convert(VARCHAR(30), Convert(TIME, Event_Time)), 101)
,[Event_Date]
,Location
,Street
,City
,[State]
,Country
,ZipCode
,[Subject]
,[Detail]
,[LeadInstructor]
,[CoInstructor]
FROM [Temp_EVT_EVENT]
) x
SMALLDATE can accept time value upto 18:00:00. But you used TIME format 18:00:00.000000 that is why it show error. Check the query and update the status.
First run this query separately:
SELECT
Convert(SMALLDATETIME, Convert(VARCHAR(30), Convert(DATE, CAST('2014-11-14' AS DATETIME), 101)) +
Convert(VARCHAR(30), ' ') + Convert(VARCHAR(30), CONVERT(VARCHAR(8), CAST('18:13:04' AS DATETIME), 108)), 101) AS column1
if you get the answer. '2014-11-14 18:13:00'
Then try to run:
SELECT
Convert(SMALLDATETIME, Convert(VARCHAR(30), Convert(DATE, CAST(Event_Date AS DATETIME), 101)) +
Convert(VARCHAR(30), ' ') + Convert(VARCHAR(30), CONVERT(VARCHAR(8), CAST(Event_Time AS DATETIME), 108)), 101) AS column1 FROM Temp_EVT_EVENT
if you get the answer correctly. Then Run:
SELECT x.*
FROM (
SELECT
Convert(SMALLDATETIME, Convert(VARCHAR(30), Convert(DATE, CAST(Event_Date AS DATETIME), 101)) +
Convert(VARCHAR(30), ' ') + Convert(VARCHAR(30), CONVERT(VARCHAR(8), CAST(Event_Time AS DATETIME), 108)), 101) AS column1
,[Event_Date]
,Location
,Street
,City
,[State]
,Country
,ZipCode
,[Subject]
,[Detail]
,[LeadInstructor]
,[CoInstructor]
FROM [Temp_EVT_EVENT]
) x
Basing on your Event_Date format, look here: Date Formats
It seems that the correct format is 120, and not 101.
So:
SELECT x.*
FROM (
SELECT
Convert(SMALLDATETIME, Convert(VARCHAR(30), Convert(DATE, Event_Date, 120)) +
Convert(VARCHAR(30), ' ') + Convert(VARCHAR(30), Convert(TIME, Event_Time)), 120)
,[Event_Date]
,Location
,Street
,City
,[State]
,Country
,ZipCode
,[Subject]
,[Detail]
,[LeadInstructor]
,[CoInstructor]
FROM [Temp_EVT_EVENT]
) x

Help with SQL to get Hits per day for today and 1 month prior

I have this SQL now:
CREATE PROCEDURE dbo.sel_Track_HitsLast30Days(
#projectID int
)
AS
BEGIN
DECLARE #FirstDay smalldatetime, #NumberOfMonths int, #priorMonth smalldatetime
set #priorMonth = (SELECT CAST(
(
STR( YEAR( dateadd(m,-1, getDate()) ) ) + '/' +
STR( MONTH( dateadd(m,-1, getDate()) ) ) + '/' +
STR( DAY( dateadd(m,-1, getDate()) ) )
)
AS DateTime
))
Select #FirstDay = #priorMonth, #NumberOfMonths = 1
;WITH Days AS (
SELECT #FirstDay as CalendarDay
UNION ALL
SELECT DATEADD(d, 1, CalendarDay) as CalendarDay
FROM Days
WHERE DATEADD(d, 1, CalendarDay) < DATEADD(m, #NumberOfMonths, #FirstDay+1)
)
SELECT calendarday,foundDate.TotalbyDate,foundDate.date FROM Days
LEFT OUTER JOIN (
SELECT
COUNT(LEFT(visitDateTime, 11)) AS TotalbyDate,substring(convert( char(10), CONVERT( char(10), visitDateTime, 121 ) ), 1, 11) AS date
FROM
dbo.TrackingData
WHERE
visitDateTime >= dateadd(d, datediff(d, 0, getdate()), -30) and projectID = #projectID
GROUP BY substring(convert( char(10), CONVERT( char(10), visitDateTime, 121 ) ), 1, 11)
) foundDate on foundDate.date = CalendarDay
order by
CalendarDay Desc
END
This works ok, but It is not taking into account months with 31 days and I am not getting back today's date for some reason.
Try this (using AdventureWorks as sample database)
DECLARE #today datetime, #NumberOfMonths int, #FirstDay smalldatetime
SELECT #today = '2004-03-09', -- getdate(), tests only
#NumberOfMonths = 1,
#FirstDay = CAST(FLOOR(CAST(
DATEADD(M, -1, #today) AS float)) AS datetime);
WITH Days AS
(
SELECT #FirstDay AS CalendarDay UNION ALL
SELECT DATEADD(d, 1, CalendarDay) AS CalendarDay FROM Days
WHERE DATEADD(d, 1, CalendarDay) < DATEADD(m, #NumberOfMonths, #FirstDay+1)
)
SELECT CONVERT(varchar(10), CalendarDay, 111) as [Date],
COUNT(TransactionDate) as [Count]
FROM Days LEFT JOIN Production.TransactionHistory
ON TransactionDate = Days.CalendarDay
GROUP BY CalendarDay
ORDER BY CalendarDay
Will output
Date Count
---------- -----------
2004/02/09 272
2004/02/10 308
2004/02/11 264
2004/02/12 265
2004/02/13 250
...
EDIT: Updated to include all interval dates
HEre is a modified version of Ruben's answer:
DECLARE #today DATETIME,
#firstDayLastMonth DATETIME,
#daysCount int
SET #today = getDate()
SET #firstDayLastMonth = Dateadd(m,-1,Dateadd(d,-Day(#today) + 1,#today))
Set #daysCount = (select datepart(dd,dateadd(dd,-1,dateadd(mm,1,cast(cast(year(#firstDayLastMonth) as varchar)+'-'+cast(month(#firstDayLastMonth) as varchar)+'-01' as datetime)))))
SELECT substring(convert( char(10), CONVERT( char(10), visitDateTime, 121 ) ), 1, 11) AS [Date], Count(* ) AS [Count]
FROM dbo.TrackingData
WHERE visitdatetime >= Dateadd(d,-#daysCount,#today)
GROUP BY substring(convert( char(10), CONVERT( char(10), visitDateTime, 121 ) ), 1, 11)
ORDER BY substring(convert( char(10), CONVERT( char(10), visitDateTime, 121 ) ), 1, 11)
OK, I got it. Rubens gave me an idea so I modified my SQL like so:
DECLARE #FirstDay SMALLDATETIME,
#NumberOfMonths INT,
#priorMonth SMALLDATETIME,
#firstDayLastMonth DateTime,
#daysCount int
set #firstDayLastMonth = dateadd(m, -1, dateadd(d, -day(getDate()) + 1, getDate()))
set #daysCount = (select datepart(dd,dateadd(dd,-1,dateadd(mm,1,cast(cast(year(#firstDayLastMonth) as varchar)+'-'+cast(month(#firstDayLastMonth) as varchar)+'-01' as datetime)))))
SET #priorMonth = (SELECT Cast((Str(Year(Dateadd(m,-1,Getdate()))) + '/' + Str(Month(Dateadd(m,-1,Getdate()))) + '/' + Str(Day(Dateadd(m,-1,Getdate())))) AS DATETIME))
Declare #before dateTime
Set #before = Dateadd(d,-#daysCount,getdate())
SELECT #FirstDay = #before,
#NumberOfMonths = 1;
WITH days
AS (SELECT #FirstDay AS calendarday
UNION ALL
SELECT Dateadd(d,1,calendarday) AS calendarday
FROM days
WHERE Dateadd(d,1,calendarday) <= Dateadd(m,#NumberOfMonths,#FirstDay))
SELECT Substring(Convert(CHAR(10),Convert(CHAR(10),calendarday,101)),
1,11) ,
founddate.totalbydate,
founddate.DATE
FROM days
LEFT OUTER JOIN (SELECT Count(Left(visitdatetime,11)) AS totalbydate,
Substring(Convert(CHAR(10),Convert(CHAR(10),visitdatetime,101)),
1,11) AS DATE
FROM dbo.trackingdata
WHERE visitdatetime >= Dateadd(d,Datediff(d,0,Getdate()),-29)
AND projectid = 131
GROUP BY Substring(Convert(CHAR(10),Convert(CHAR(10),visitdatetime,101)),
1,11)) founddate
ON founddate.DATE = Substring(Convert(CHAR(10),Convert(CHAR(10),calendarday,101)),
1,11)

Resources