Getting Error when converting to datetime :Date Column + Time Column - sql-server

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

Related

Creating Dynamic Pivot Table Column Names

I have created a pivot table with hard coded column names. The pivot table simply keeps a rolling sum of sales by qty (current month + 11 months back).
It was my first time using the PIVOT function properly and the code works fine.
SELECT
Item_Code_Desc,
ISNULL([Current],0) AS [Current],
ISNULL([1],0) AS [1],
ISNULL([2],0) AS [2],
ISNULL([3],0) AS [3],
ISNULL([4],0) AS [4],
ISNULL([5],0) AS [5],
ISNULL([6],0) AS [6],
ISNULL([7],0) AS [7],
ISNULL([8],0) AS [8],
ISNULL([9],0) AS [9],
ISNULL([10],0) AS [10],
ISNULL([11],0) AS [11]
FROM
(SELECT
CONCAT(ST.Code,' - ', ST.Description_1) AS Item_Code_Desc,
STT.ActualQuantity AS Qty,
CASE
WHEN MONTH(STT.TxDate) = MONTH(GETDATE()) THEN 'Current'
WHEN MONTH(STT.TxDate) = MONTH(DATEADD(MONTH, -1, GETDATE())) THEN '1'
WHEN MONTH(STT.TxDate) = MONTH(DATEADD(MONTH, -2, GETDATE())) THEN '2'
WHEN MONTH(STT.TxDate) = MONTH(DATEADD(MONTH, -3, GETDATE())) THEN '3'
WHEN MONTH(STT.TxDate) = MONTH(DATEADD(MONTH, -4, GETDATE())) THEN '4'
WHEN MONTH(STT.TxDate) = MONTH(DATEADD(MONTH, -5, GETDATE())) THEN '5'
WHEN MONTH(STT.TxDate) = MONTH(DATEADD(MONTH, -6, GETDATE())) THEN '6'
WHEN MONTH(STT.TxDate) = MONTH(DATEADD(MONTH, -7, GETDATE())) THEN '7'
WHEN MONTH(STT.TxDate) = MONTH(DATEADD(MONTH, -8, GETDATE())) THEN '8'
WHEN MONTH(STT.TxDate) = MONTH(DATEADD(MONTH, -9, GETDATE())) THEN '9'
WHEN MONTH(STT.TxDate) = MONTH(DATEADD(MONTH, -10, GETDATE())) THEN '10'
WHEN MONTH(STT.TxDate) = MONTH(DATEADD(MONTH, -11, GETDATE())) THEN '11'
ELSE '0'
END AS [Period]
FROM
_bvSTTransactionsFull AS STT
INNER JOIN
StkItem AS ST ON STT.AccountLink = ST.StockLink
WHERE
STT.TxDate >= DATEADD(MONTH, -11, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))
AND STT.Module = 'AR') AS P
PIVOT
(SUM(P.Qty)
FOR P.Period IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[Current])
) AS PVT
To make the output more dynamic, I wanted to rather show the month and year as the field heading, rather than just the 1,2,3 etc.
To attempt this, I first took out the original CASE, and used the CONCAT function to get the desired result
CONCAT(DATENAME(MONTH,STT.TxDate),' ',YEAR(STT.TxDate)) AS [Period],
Now that the sub-query was showing the transaction date in the format "mmmm yyyy", I wanted the table to pivot on this. I did start wondering how it was going to do this as I was reaching the end, as the column names are not hard coded anymore.
After trying
PIVOT (
SUM(P.Qty)
FOR CONCAT(DATENAME(MONTH,P.TxDate),' ',YEAR(P.TxDate))
) AS PVT
And many other variations I did do some research, and I see this process is slightly more complex than I thought.
I haven't used the STUFF and FOR XML PATH before. I have attempted to convert the above into the examples I have found on the net. But I'm trying in vein as I don't understand the core logic of what I am trying to do.
Please could I have assistance with not only how to get the pivot dynamic, but perhaps some notes to further understand what is happening. Really appreciate some help on this!
After Attempting
This is my attempt to get it right:
DECLARE
#Cols NVARCHAR(MAX),
#Query NVARCHAR(MAX),
#Module NVARCHAR = 'AR'
SELECT
#Cols = STUFF((SELECT DISTINCT ',' + 'CONCAT(DATENAME(MONTH, STT.TxDate),,YEAR(STT.TxDate))' + QUOTENAME(NAME)
FROM _bvSTTransactionsFull AS STT
WHERE STT.Module = 'AR'
FOR XML PATH (''), TYPE).VALUE('.','NVARCHAR(MAX)'),1,1,'')
SELECT
#Query = '
SELECT
Item_Code,
Item_Desc,
' +''''+ #Cols + '''''
FROM
(SELECT
ST.Code AS Item_Code,
ST.Description_1 AS Item_Desc,
STT.ActualQuantity AS Qty,
CONCAT(DATENAME(MONTH, STT.TxDate),,YEAR(STT.TxDate)) AS [Period]
FROM
_bvSTTransactionsFull AS STT
INNER JOIN
StkItem AS ST ON STT.AccountLink = ST.StockLink
WHERE
STT.TxDate >= DATEADD(MONTH, -13, DATEADD(MONTH, DATEDIFF(MONTH, 0,
GETDATE()), 0))
AND STT.Module = '+ #Module +') AS P
PIVOT
(SUM(P.Qty)
FOR P.Period IN ('+#cols+')
) AS PVT '
PRINT #Query
EXEC (#Query)
But I'm getting the following error:
Msg 207, Level 16, State 1, Line 7
Invalid column name 'NAME'.
Where am I off here?
Your result is correct above however, you will not have your columns sorted by the correct date...
The below would cater for that:
DECLARE
#Cols1 VARCHAR(MAX),
#Cols2 VARCHAR(MAX),
#Query VARCHAR(MAX),
#Period VARCHAR(MAX) = -13 ; --/ Select number of months to view back on (excluding current month) \--
declare #tmptbl table (PeriodDate datetime, col1 varchar(100), col2 varchar(100))
insert into #tmptbl (PeriodDate, col1, col2)
SELECT DISTINCT dPeriodDate,'ISNULL('+ QUOTENAME(CONCAT(DATENAME(MONTH, dPeriodDate),' ',YEAR(dPeriodDate)))+',0) AS' + QUOTENAME(CONCAT(DATENAME(MONTH, dPeriodDate),' ',YEAR(dPeriodDate))) col1
, QUOTENAME(CONCAT(DATENAME(MONTH, dPeriodDate),' ',YEAR(dPeriodDate))) col2
FROM _bvSTTransactionsFull AS S join _etblPeriod p on EOMONTH(s.TxDate) = p.dPeriodDate
WHERE S.Module = 'AR' AND S.TxDate > = DATEADD(MONTH, -13, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))
SELECT
#Cols1 = STUFF((SELECT ',' + col1
FROM #tmptbl order by PeriodDate
FOR XML PATH (''), TYPE).value('.','NVARCHAR(MAX)'),1,1,'') --/ allows the first SELECT fields to have the ISNULL function and Alias \--
SELECT
#Cols2 = STUFF((SELECT ',' + col2
FROM #tmptbl order by PeriodDate
FOR XML PATH (''), TYPE).value('.','NVARCHAR(MAX)'),1,1,'') --/ becasue of the need for ISNULL above, second #Cols needed for the Pivot (pivot cannot have ISNULL in it) \--
SELECT
#Query =
'SELECT
Item_Code_Desc,
'+#Cols1+'
FROM
(SELECT
CONCAT(ST.Code,'' - '', ST.Description_1) AS Item_Code_Desc,
STT.ActualQuantity AS Qty,
CONCAT(DATENAME(MONTH, STT.TxDate),'' '',YEAR(STT.TxDate)) AS [Period]
FROM
_bvSTTransactionsFull AS STT
INNER JOIN
StkItem AS ST ON STT.AccountLink = ST.StockLink
WHERE
STT.TxDate >= DATEADD(MONTH, '+#Period+', DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))
AND STT.Module = ''AR'') AS P
PIVOT
(SUM(P.Qty)
FOR P.Period IN ('+#cols2+')
) AS PVT '
PRINT #Query
EXEC (#Query)
I left the changes I made in small caps for you to see the changes...
Solved :)
DECLARE
#Cols1 VARCHAR(MAX),
#Cols2 VARCHAR(MAX),
#Query VARCHAR(MAX),
#Period VARCHAR(MAX) = -12 ; --/ Select number of months to view back on (excluding current month) \--
SELECT
#Cols1 = STUFF((SELECT DISTINCT ',' +'ISNULL('+ QUOTENAME(CONCAT(DATENAME(MONTH, S.TxDate),' ',YEAR(S.TxDate)))+',0) AS' + QUOTENAME(CONCAT(DATENAME(MONTH, S.TxDate),' ',YEAR(S.TxDate)))
FROM _bvSTTransactionsFull AS S
WHERE S.Module = 'AR' AND S.TxDate > = DATEADD(MONTH, -13, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))
FOR XML PATH (''), TYPE).value('.','NVARCHAR(MAX)'),1,1,'') --/ allows the first SELECT fields to have the ISNULL function and Alias \--
SELECT
#Cols2 = STUFF((SELECT DISTINCT ',' + QUOTENAME(CONCAT(DATENAME(MONTH, S.TxDate),' ',YEAR(S.TxDate)))
FROM _bvSTTransactionsFull AS S
WHERE S.Module = 'AR' AND S.TxDate > = DATEADD(MONTH, -13, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))
FOR XML PATH (''), TYPE).value('.','NVARCHAR(MAX)'),1,1,'') --/ becasue of the need for ISNULL above, second #Cols needed for the Pivot (pivot cannot have ISNULL in it) \--
SELECT
#Query =
'SELECT
Item_Code_Desc,
'+#Cols1+'
FROM
(SELECT
CONCAT(ST.Code,'' - '', ST.Description_1) AS Item_Code_Desc,
STT.ActualQuantity AS Qty,
CONCAT(DATENAME(MONTH, STT.TxDate),'' '',YEAR(STT.TxDate)) AS [Period]
FROM
_bvSTTransactionsFull AS STT
INNER JOIN
StkItem AS ST ON STT.AccountLink = ST.StockLink
WHERE
STT.TxDate >= DATEADD(MONTH, '+#Period+', DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))
AND STT.Module = ''AR'') AS P
PIVOT
(SUM(P.Qty)
FOR P.Period IN ('+#cols2+')
) AS PVT '
PRINT #Query
EXEC (#Query)

Best way to incorporate a query inside of the PIVOT IN list?

so I'm trying to come up with a payroll worksheet and here's what I got:
SELECT * FROM
(
SELECT
CAST(ad.EmplName AS NVARCHAR(MAX)) AS [EmplName],
CONVERT(VARCHAR(30), CAST(ad.TicketDate AS DATE), 1) AS [TicketDate],
ROUND(ad.TotActTime, 2) AS [TotalHrs]
FROM AttendDet ad
WHERE ad.EmplCode IS NOT NULL
AND ad.AttendCode <> '9999'
AND CONVERT(DATE, ad.TicketDate) BETWEEN '20181022' AND '20181027'
) AS BaseData
PIVOT
(
SUM(BaseData.TotalHrs)
FOR BaseData.TicketDate
IN
(
[10/22/18],[10/23/18],[10/24/18],[10/25/18],[10/26/18],[10/27/18], [10/28/18]
)
) AS PivotTable
Now that query works as expected, results are as follows:
The problem is having to type in the dates inside of IN within PIVOT. What would be the best way to do this automatically with a list from a query?
If I have a list of dates and let's say I always wanted to look at the previous week, then the code below can generate that:
SELECT
CONVERT(VARCHAR(30), CAST(DATEADD(dd,((DATEDIFF(dd,'17530101',GETDATE())/7)*7)-7,'17530101') AS DATE), 1)
UNION
SELECT
CONVERT(VARCHAR(30), CAST(DATEADD(dd,((DATEDIFF(dd,'17530101',GETDATE())/7)*7)-6,'17530101') AS DATE), 1)
UNION
SELECT
CONVERT(VARCHAR(30), CAST(DATEADD(dd,((DATEDIFF(dd,'17530101',GETDATE())/7)*7)-5,'17530101') AS DATE), 1)
UNION
SELECT
CONVERT(VARCHAR(30), CAST(DATEADD(dd,((DATEDIFF(dd,'17530101',GETDATE())/7)*7)-4,'17530101') AS DATE), 1)
UNION
SELECT
CONVERT(VARCHAR(30), CAST(DATEADD(dd,((DATEDIFF(dd,'17530101',GETDATE())/7)*7)-3,'17530101') AS DATE), 1)
UNION
SELECT
CONVERT(VARCHAR(30), CAST(DATEADD(dd,((DATEDIFF(dd,'17530101',GETDATE())/7)*7)-2,'17530101') AS DATE), 1)
UNION
SELECT
CONVERT(VARCHAR(30), CAST(DATEADD(dd,((DATEDIFF(dd,'17530101',GETDATE())/7)*7)-1,'17530101') AS DATE), 1)
Problem is, I have no idea how to incorporate that into my IN. I've looked up some questions that refer to doing it via dynamic SQL, but honestly, I've no idea what that even is and I'm having a hard time trying to apply those examples to my case. Is there another way of doing this? Any help is appreciated, thanks in advance
I have been working something related these days. You may try this one; review and update it looking into your data. For further explanation, may you review the link attached on the comment.
Declare #start_date datetime
Declare #end_date datetime
Declare #attendance_code int
DECLARE #columns NVARCHAR(MAX), #sql NVARCHAR(MAX);
SET #columns = N'';
SELECT #columns += N', p.' + QUOTENAME(BASEData.TicketDate)
FROM (SELECT
CAST(ad.EmplName AS NVARCHAR(MAX)) AS [EmplName],
CONVERT(VARCHAR(30), CAST(ad.TicketDate AS DATE), 1) AS [TicketDate],
ROUND(ad.TotActTime, 2) AS [TotalHrs]
FROM AttendDet ad
GROUP BY p.BASEData.TicketDate) AS x;
SET #sql = N'
SELECT ' + STUFF(#columns,1,2,'') + '
(
SELECT
CAST(ad.EmplName AS NVARCHAR(MAX)) AS [EmplName],
CONVERT(VARCHAR(30), CAST(ad.TicketDate AS DATE), 1) AS [TicketDate],
ROUND(ad.TotActTime, 2) AS [TotalHrs]
FROM AttendDet ad
WHERE ad.EmplCode IS NOT NULL
AND ad.AttendCode <> '''#attendance_code'''
AND CONVERT(DATE, ad.TicketDate) BETWEEN + '''CONVERT(VARCHAR, #start_date)''' AND + '''CONVERT(VARCHAR,#end_date)'''
) AS BaseData
PIVOT
(
SUM(BaseData.TotalHrs)
FOR BaseData.TicketDate
IN
(' STUFF(REPLACE(#columns, ', p.[', ',['), 1, 1, '')
) AS PivotTable;';
PRINT #sql;
EXEC sp_executesql #sql;

SQL Server date time conversion issue

Below is the SQL server query I am using,
SELECT
*,
CONCAT(CONVERT(date, startdate, 104), RIGHT(+' '+ CONVERT(VARCHAR, startTime), 8)) AS NewDate,
CONCAT(CONVERT(date, '7.8.2018', 104), RIGHT(+' '+ CONVERT(VARCHAR, '3:51:23'), 8)) AS NewDate2,
CASE
WHEN CONCAT(CONVERT(date, startdate, 104), RIGHT(+' '+ CONVERT(VARCHAR, startTime), 8)) < CONCAT(CONVERT(date, '7.8.2018', 104), RIGHT(+' '+ CONVERT(VARCHAR, '3:51:23'), 8))
THEN '1'
ELSE '0'
END AS comment
FROM
[dbo].[LMT2_ServerLicenseUser]
WHERE
CONCAT(CONVERT(date, startdate, 104), RIGHT(+' '+ CONVERT(VARCHAR, startTime), 8)) > CONCAT(CONVERT(date, '7.8.2018', 104), RIGHT(+' '+ CONVERT(VARCHAR, '3:51:23'), 8))
and the output is shown below in the screenshot:
I am comparing columns 'NewDate' and 'NewDate2' here and if the condition is true then assigning value in a new column called 'comment' which is showing wrong values.
Please help me to understand where is the issue is it a date time conversions issue or something else.
You can try use to cast(startdate as datetime) + cast(startTime as datetime) let the column Convert to DateTime Type then compare, becasue you can't compare string DateTimeformat.
Select *
,CONCAT( CONVERT(date, startdate, 104), RIGHT(+' '+ CONVERT(VARCHAR,startTime),8)) AS NewDate
,CONCAT( CONVERT(date, '7.8.2018', 104), RIGHT(+' '+ CONVERT(VARCHAR,'3:51:23'),8)) AS NewDate2
,case
cast(startdate as datetime) + cast(startTime as datetime) > cast('7.8.2018' as datetime) + cast('3:51:23' as datetime)
then '1'
else '0'
end as comment
from [dbo].[LMT2_ServerLicenseUser]

Use MAX(Date) value inside a SQL recursion

I have SQL query with performs recursion based on selected Min(Date) and Max(Date) from more than 1 table. But when i try to run the query it throws GROUP BY, HAVING, or aggregate functions are not allowed in the recursive part of a recursive common table expression 'ctedaterange'. exception. I also tried using Top 1 Date but still no hope.
SQL Query
ALTER VIEW [dbo].[CYExtraction]
AS
WITH ctedaterange
AS (SELECT
[Dates] = (SELECT
MIN(CreatedOn) AS CreatedOn
FROM (SELECT
MIN(CreatedOn) AS CreatedOn
FROM (SELECT
MIN(CreatedOn) AS CreatedOn
FROM Items) AS it
UNION ALL
SELECT
*
FROM (SELECT
MIN(CreatedOn) AS CreatedOn
FROM Bibs) AS bib
UNION ALL
SELECT
*
FROM (SELECT
MIN(CreatedOn) AS CreatedOn
FROM Porders) AS po) AS AllItems)
UNION ALL
SELECT
[dates] + 1
FROM ctedaterange
WHERE [dates] + 1 <= (SELECT
MAX(CreatedOn) AS CreatedOn
FROM (SELECT
MAX(CreatedOn) AS CreatedOn
FROM (SELECT
MAX(CreatedOn) AS CreatedOn
FROM Items) AS it
UNION ALL
SELECT
*
FROM (SELECT
MAX(CreatedOn) AS CreatedOn
FROM Bibs) AS bib
UNION ALL
SELECT
*
FROM (SELECT
MAX(CreatedOn) AS CreatedOn
FROM Porders) AS po) AS AllItems))
SELECT
[Dates] AS PK_Date,
DATENAME(MONTH, [Dates]) + ' ' + CAST(YEAR([Dates]) AS varchar(4)) AS
Month,
CASE
WHEN DATEPART(m, [Dates]) <= 3 THEN 'Q1 ' + CAST(YEAR([Dates]) AS varchar(4))
ELSE CASE
WHEN DATEPART(m, [Dates]) <= 6 THEN 'Q2 ' + CAST(YEAR([Dates]) AS varchar(4))
ELSE CASE
WHEN DATEPART(m, [Dates]) <= 9 THEN 'Q3 ' + CAST(YEAR([Dates]) AS varchar(4))
ELSE CASE
WHEN DATEPART(m, [Dates]) <= 12 THEN 'Q4 ' + CAST(YEAR([Dates]) AS varchar(4))
ELSE ''
END
END
END
END AS 'Quarter',
CASE
WHEN DATEPART(m, [Dates]) <= 6 THEN 'HY1 ' + CAST(YEAR([Dates]) AS varchar(4))
ELSE CASE
WHEN DATEPART(m, [Dates]) <= 12 THEN 'HY2 ' + CAST(YEAR([Dates]) AS varchar(4))
ELSE ''
END
END AS 'HalfYear',
YEAR([Dates]) AS 'Year',
CAST('1-' AS varchar(5)) + CAST(DATEPART(M, [Dates]) AS varchar(10)) + '-' + CAST(YEAR([Dates]) AS varchar(4)) AS DateName
FROM ctedaterange
GO
The main thing is that I need to wrap it inside my SQL Views. Any help to my problem will be appreciated.
Thanks,
You can move the aggregations to an extra cte, so this might be what you want:
ALTER VIEW [dbo].[CYExtraction]
(PK_Date, [Month], [Quarter], [HalfYear], [Year], [DateName])
AS
WITH cteAllItems (mindates, maxdates) AS (
SELECT MIN(CreatedOn), MAX(CreatedOn) FROM Items
UNION ALL
SELECT MIN(CreatedOn), MAX(CreatedOn) FROM Bibs
UNION ALL
SELECT MIN(CreatedOn), MAX(CreatedOn) FROM Porders
),
ctedaterange (Dates, MaxDate) AS (
SELECT MIN(mindates), MAX(maxdates)
FROM cteAllItems
UNION ALL
SELECT DATEADD(day, 1, Dates), MaxDate
FROM ctedaterange
WHERE DATEADD(day, 1, Dates) <= MaxDate
)
SELECT
Dates AS PK_Date,
DATENAME(MONTH, Dates) + N' ' + DATENAME(YEAR, Dates),
N'Q' + DATENAME(QUARTER, Dates) + N' ' + DATENAME(YEAR, Dates),
N'HY' + CAST((MONTH(Dates)-1)/6+1 AS nvarchar(1)) + N' ' + DATENAME(YEAR, Dates),
YEAR(Dates),
CONVERT(nvarchar(10), DATEADD(MONTH, DATEDIFF(MONTH, 0, Dates), 0), 105)
FROM ctedaterange
GO

Comparing DateTIme Column value with DateTime String 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 )

Resources