Convert a varchar variable to a datetime variable - sql-server

I have a data with a few columns. One of them (Col1) is a varchar variable.
I'll give a sample of a few values :
Col1:
'2013-01-01 00:00:00:000'
NULL
'2013-01-01 00:00:00:000'
I'n the design I'm trying to change the data type from a varchar variable into a datetime variable and it throws me an error:
"Unable to modify table. conversion failed when converting date and/or time from a character string".
Any suggestions to remove the problem?

You have to convert the varchar to datetime. You can use cast or convert function. You should store your date value in a proper format in your varchar column.
I assume you are using SQL server 2012.
Try like this,
DECLARE #d TABLE (col1 VARCHAR(50))
INSERT INTO #d
VALUES ('2013-01-01 00:00:00:000')
,(NULL)
,('2013-01-01 00:00:00:000')
SELECT convert(DATETIME, Col1) AS DATE
In case the above query returns error then you can use try_convert function.
(this would ignore your bad format data) Note: You should take necessary action to your bad data.
SELECT try_convert(DATETIME, Col1) AS DATE
FROM #d
FROM #d

You can use ISDATE() to filter the date columns and simply CAST the column.
In the MSDN it describes as
Returns 1 if the expression is a valid date, time, or datetime value; otherwise, 0.
Sample execution with given data:
DECLARE #TestTable TABLE (Col1 VARCHAR(50))
INSERT INTO #TestTable (Col1) VALUES
('2013-01-01 00:00:00:000'),
(NULL),
('2013-01-01 00:00:00:000');
SELECT CAST(Col1 AS DATETIME)
FROM #TestTable
WHERE ISDATE(Col1) = 1
Output:
Col1
------------------------
2013-01-01 00:00:00:000
2013-01-01 00:00:00:000

Hi #Jordan1200 as suggested above the following should be a quick and simple fix;
CAST(Col1 AS DATETIME) AS Col1

Related

Conversion in SQL for secondary parameter

I have the below sample table script:
create table #temp
(
field_01 int,
field_02 varchar(20)
)
insert into #temp
select
isnull(a.id,'UN'),
a.textcol
from
table1 a...
In the above table script, to insert value for field_01 should be either a.id(which is an int) or UN. Field_01 is integer and I'm confused about converting UN.
Getting conversion error:
Conversion failed when converting the varchar value 'UN' to data type int.
Should I convert the entire row or just UN part like isnull(a.id,CONVERT(INT, 'UN'))
If you just want to select the data you need to convert the whole ISNULL statement
select
convert(varchar,isnull(a.id,'UN')) as id,
a.textcol
from table1 a...
BUT if you want to insert it, then you can't. You have to change the DDL of the table in order to insert a varchar in an INT column. You have to change the column from INT to VARCHAR, otherwise it is impossible.
EDIT: To clarify as scsimon has said I'll add the complete query from the example given.
create table #temp
(
field_01 varchar(20),
field_02 varchar(20)
)
insert into #temp
select
id,
a.textcol
from table1 a...
select
isnull(field_01,'UN') as field_01,
field_02
from #temp

SQL Server 2008 inconsistent results when converting datetime to varchar

I have a table with two datetime columns and I'm trying to convert them to an iso string format using the following query:
select
CONVERT(VARCHAR(23), date1, 126) as date1,
CONVERT(VARCHAR(23), date2, 126) as date2
from
some_table
But I'm getting two different results, one with milliseconds and one without
date1 date2
2015-03-11T05:16:04.663 2015-03-11T05:15:43
I've looked at the create table script and they are both defined as datetime. I have no clue how the data is being inserted.
How can I get both columns to return with milliseconds ?
SQL Server "helpfully" will trim the milliseconds portion if it's entirely 0. If you need the 0 milliseconds included (I can't imagine what you're doing where you need .000 to be included) then you'll have to detect the trimming and re-add them:
;With Converted as (
--Your existing query. For this example, I'm just using one date:
select CONVERT(varchar(23),CONVERT(datetime,'2015-03-01T05:15:43.000'),126) as date2
)
select
CASE
WHEN LEN(date2) = 19 THEN date2 + '.000'
ELSE date2
END as date2
from Converted
(And, again if for some bizarre reason you really need the end result to be a varchar(23) rather than a varchar(27) you'll have to add another CONVERT that wraps the CASE expression because the system's not smart enough to realise that any value that the CASE returns could always fit in a varchar(23))
It is becouse the second date has 0 ms.
CREATE TABLE #Test ( date1 datetime, date2 datetime)
INSERT INTO #Test VALUES ('2015-03-11 05:16:04.663','2015-03-11 05:15:43' )
INSERT INTO #Test VALUES ('2015-03-11 05:16:04','2015-03-11 05:15:43.55' )
select
CONVERT(VARCHAR(23), date1, 126) as date1,
CONVERT(VARCHAR(23), date2, 126) as date2
from
#Test
Check this example.

Sum of datetime column in sql 05

I have a column named as "total_hours_worked" in my sql table which is of "datetime" datatype
I want to find out the total of "total hours worked in sql server".
How to do this?
I googled but didn't got a practical solution.
Something like this if I understand your data correctly.
declare #T table
(
total_hours_worked datetime
)
insert into #T values ('05:30:00')
insert into #T values ('10:00:00')
insert into #T values ('15:00:00')
select sum(datediff(minute, 0, total_hours_worked)) / 60.0 as hours_worked
from #T
Result:
hours_worked
---------------------------------------
30.500000
If you only need to store the hours you should consider an integer datatype instead of datetime. It will be more efficient and easier to deal with.
Try this.Here I considered seconds also.
declare #T table
(
total_hours_worked datetime
)
insert into #T values ('05:30:00')
insert into #T values ('10:00:00')
insert into #T values ('15:00:00')
insert into #T values ('05:25:45')
select SUM((DATEPART(hh,total_hours_worked)*60)+DATEPART(mi,total_hours_worked)+(DATEPART(ss,total_hours_worked)/(60.0)))/60.0 as TotalHours from #T

T-SQL query with date range

I have a fairly weird 'bug' with a simple query, and I vaguely remember reading the reason for it somewhere a long time ago but would love someone to refresh my memory.
The table is a basic ID, Datetime table.
The query is:
select ID, Datetime from Table where Datetime <= '2010-03-31 23:59:59'
The problem is that the query results include results where the Datetime is '2010-04-01 00:00:00'. The next day. Which it shouldn't.
Anyone?
Cheers
Moo
Take a look at How Are Dates Stored In SQL Server? and How Does Between Work With Dates In SQL Server?
If that is a smalldatetime it has 1 minute precision so if rounds up, for datetime it is 300 miliseconds
example
DECLARE #d DATETIME
SELECT #d = '2001-12-31 23:59:59.999'
SELECT #d
2002-01-01 00:00:00.000
DECLARE #d DATETIME
SELECT #d = '2001-12-31 23:59:59.998'
SELECT #d
2001-12-31 23:59:59.997
Always use less than next day at midnight, in your case
< '20100401'
try doing it like:
select ID, Datetime from Table where Datetime < '2010-04-01'
I always floor the datetime and increment the day and just use "<" less than.
to floor a datetime to just the day use:
SELECT DATEADD(day,DATEDIFF(day,0, GETDATE() ),0)
you can easily increment a datetime by using addition:
SELECT GETDATE()+1
by using the '23:59:59' you can miss rows, try it out:
DECLARE #YourTable table (RowID int, DateOf datetime)
INSERT INTO #YourTable VALUES (1,'2010-03-31 10:00')
INSERT INTO #YourTable VALUES (2,'2010-03-31')
INSERT INTO #YourTable VALUES (3,'2010-03-31 23:59:59')
INSERT INTO #YourTable VALUES (4,'2010-03-31 23:59:59.887')
INSERT INTO #YourTable VALUES (5,'2010-04-01')
INSERT INTO #YourTable VALUES (6,'2010-04-01 10:00')
select * from #YourTable where DateOf <= '2010-03-31 23:59:59'
OUTPUT
RowID DateOf
----------- -----------------------
1 2010-03-31 10:00:00.000
2 2010-03-31 00:00:00.000
3 2010-03-31 23:59:59.000
(3 row(s) affected
this query is wrong, because it does not find the missed rowID=4 record.
if you try to fix this with:
select * from #YourTable where DateOf <= '2010-03-31 23:59:59.999'
then RowID=5 will be included as well, which is wrong.
It's very odd that you are seeing that; I don't know why. But I will suggest that you write the query this way instead:
select ID, Datetime from Table where Datetime < '2010-04-01'

IsNumeric Time value problem

Table1
Time
10:00:00
12:00:00
Absent
14:00:00
Holiday
...,
Time column Datatype is varchar
I want to check the time column value is numeric then 'Present'
Tried Query
Select case when isnumeric(time) then 'Present' else time end as time from table1
Showing error in 'then'
How to modify my query according to my requirement
Need Query Help
Try using ISDATE
Returns 1 if the expression is a valid
date, time, or datetime value;
otherwise, 0.
Something like
DECLARE #Table TABLE(
[Time] VARCHAR(50)
)
INSERT INTO #Table SELECT '10:00:00'
INSERT INTO #Table SELECT '12:00:00'
INSERT INTO #Table SELECT 'Absent'
INSERT INTO #Table SELECT '14:00:00'
INSERT INTO #Table SELECT 'Holiday'
SELECT *,
ISDATE(Time),
case when ISDATE(time) != 0 then 'Present' else time end
FROM #Table

Resources