How to sql server difference query datetime varchar - sql

I have variable time, format is varchar(8) in SQL Server
how result like this ?
I try with datediff.. but I can not do it.. because variable is type varchar...
sql server 2008 r2

Before using Datediff use Convert function to convert the varchar data into date
select datediff(dd,convert(date,date2),convert(date,date1))
From Yourtable
If you have any bad data which cannot be converted to date then who may have to filter out those data before converting to date.
If you are using Sql Server 2012+ then use TRY_CONVERT
select datediff(dd,try_convert(date,date2),try_convert(date,date1))
From Yourtable
Sqlfiddle Demo

Convert the varchar date into a proper date:
select datediff(day, cast(date1 as date), cast(date2 as date)) from your_table

Select
Datediff(day,
cast(left('20150201', 4) + '-' +
substring('20150201', 5, 2) + '-' +
right('20150201', 2) as DateTime),
cast(left('20150220', 4) + '-' +
substring('20150220', 5, 2) + '-' +
right('20150220', 2) as DateTime))
Try this to convert varchar into datetime

Related

Change date format dd/mm/yyyy to yyyy-mm-dd

am working in SQL Server 2008, while merging I got error like
conversion failed when converting datetime from character string
select *
from table_name
where cast(f_datetime as date) <=
cast(cast(datepart(year,cast(convert(varchar(250),#Year,103) as date) )as varchar(250))+ '-'+ cast(datepart(MM,cast(convert(varchar(10),#month,103) as varchar(50))+'-01' as date)
I cannot speak to the cast() on f_datetime. But for the rest, you can do:
where cast(f_datetime as date) <= convert(date, convert(varchar(250), #year * 10000 + #month * 100 + 1))
This simplifies the calculation, and prevents things like #year from being treated as a date due to the convert() function.
I assume your f_datetime field format is "dd/mm/yyyy". If yes you can easily convert this field instead of trying to merge and convert #year and #month fields. check this query :
SELECT *
FROM table_name
WHERE CONVERT(DATE,f_datetime,103)<= CAST(CONVERT(VARCHAR, #year) + '-' + CONVERT(VARCHAR, #month) + '-' + '01' AS DATE)

SQL Date/Time Format

How to convert date/time from 20150323153528 to 2015-03-23 15:35:28.000. I need this to filter based on the getdate(). Thanks in advance.
Select * from table
Where 20150323153528 > GETDATE() - 7
Statement to convert date to your requirement
DECLARE #Date varchar(20) = '20150323153528'
Select * from table Where
CONVERT(DATETIME, CONVERT(CHAR(8), #Date), 121) + ' ' + stuff(stuff(right('000000' + cast(#Date as varchar),6),5,0,':'),3,0,':') as DATETIME > GETDATE() - 7
In MS SQL you could use
DECLARE #Date varchar(20) = '20150323153528'
Select * from table Where CAST(convert(varchar,#Date) as datetime) > GETDATE() - 7
Please read this page.
SELECT convert(varchar, getdate(), 120) — yyyy-mm-dd hh:mm:ss(24h)
Note: I assume this is a Microsoft SQL Server environment using T-SQL:
The formatting of date / datetime values is not a concern of T-SQL. You should do that in your presentation-layer (i.e. your frontend code).
If you have date/time values represented as integers of the form 20150323153528 then you cannot use them in T-SQL. You need to convert them to strings (preferably in ISO-8601 format) for SQL Server to successfully internally convert them to datetime (or datetimeoffset) values which can then be compared with other datetime values.
I suggest performing the conversion in your application code before you send it to SQL, as a datetime-typed parameter value, like so:
Int32 weirdDateValue = 20150323153528;
String s = weirdDateValue.ToString( CultureInfo.InvariantCulture );
String dtValueAsIso8601 = String.Format("{0}-{1}-{2} {3}:{4}:{5}.{6}",
s.Substring(0, 4), s.Substring(4, 2), s.Substring(6, 2),
s.Substring(8, 2), s.Substring(10, 2), s.Substring(12, 2), s.Substring(14)
);
DateTime dtValue = DateTime.ParseExact( dtValueAsIso8601, "yyyy-MM-dd HH:mm:ss.fff" );
cmd.Parameters.Add("#dtValue", SqlDbType.DateTime).Value = dtValue;
In T-SQL the process is pretty much the same, except using MID - note that MID uses 1-based character indexes instead of 0-based:
DECLARE #input int = 20150323153528
DECLARE #s varchar( 14 ) = CONVERT( #input, nvarchar(14) )
DECLARE #dtStr varchar( 24 ) = MID( #s, 1, 2 ) + '-' + MID( #s, 3, 2 ) + '-' + MID( #s, 5, 2 ) + ' ' + -- etc...
DECLARE #dt datetime = CONVERT( #dtStr, datetime )
SELECT
*
FROM
[table]
WHERE
#dt > GETDATE() - 7
If the integer values are stored in an actual column instead of a parameter you'll need to convert the logic into a scalar UDF which performs the conversion. I strongly suggest you change the table's design to add a strongly-typed datetime column and permanently store the value there, and then drop the datetime-as-int column:
CREATE FUNCTION ConvertIntDateIntoDateTime(#dateAsInt int) RETURNS datetime AS
BEGIN
-- same code as above minus the SELECT statement
RETURN #dt
END
Used in an inner subquery to allow the data to be accessed in WHERE statements, like so:
SELECT
*
FROM
(
SELECT
*,
dbo.ConvertIntDateIntoDateTime( someDateColumn ) AS someDateColumn2
FROM
[table]
) AS FixedTable
WHERE
FixedTable.someDateColumn2 > GETDATE() - 7

SQL Server Query Date convert Issue

I want to add where condition in my query like 2012-10-05 00:29:06.338 <= Today'sdatetime however I am getting the issue.
Please help me to sort out this issue.
My query is given below :
Select * from table1
where
CONVERT(varchar(12),'2012-10-05 00:29:06.338', 106) + ' ' + CONVERT(varchar(12),'2012-10-05 00:29:06.338', 108) <= CONVERT(varchar(12), GETDATE(),106) + ' 23:59:00.000'
You can't do date comparisons by converting both values to a varchar. You need to convert the values to datetime and compare.
If you have a column in your database named col1 that is a datetime, you can compare this directly to GETDATE().
For example:
select * from table1 where col1 > GETDATE()
If you really need to compare a date with a string you can explicitly convert to datetime:
Select *
from table1
where CONVERT(DATETIME,'2012-10-05 00:29:06.338') <= GETDATE()
OR you can let SQL Server implicitly do the conversion for you:
Select *
from table1
where '2012-10-05 00:29:06.338' <= GETDATE()
You're trying to evaluate a string as a date:
Select '8'
where
CONVERT(DATETIME,CONVERT(varchar,Col1, 101))
+ ' ' + CONVERT(DATETIME,CONVERT(varchar,Col1,108))
<= CONVERT(DATETIME,CONVERT(varchar, GETDATE(),101))+' ' + CONVERT(DATETIME,CONVERT(varchar,'23:59:00.000', 108))

combine 2 varchar column's data and convert to datetime

I have 2 columns in a table of varchar datatype.
date and type are the column names in table.
the data present in the table looks like this
date time
20090610 132713
20090610 132734
i need ms sql server query to concatenate these 2 columns data and display as datetime format.
Note :
1. the datatype of those 2 columns cannot be changed now.
2. i tried
select convert(datetime,date + time)
it says "Conversion failed when converting date and/or time from character string."
Suggest the possible solution.
This will return a datetime. The bottom line is to be replaced by your table
select convert(datetime,date,112)+
coalesce(stuff(stuff(rtrim(time), 5,0,':'), 3,0,':'), '') newdate
from
(VALUES ('20090610','132713'),('20090610', '132734'),('20090610', ' ')) yourtable(date,time)
Result:
newdate
2009-06-10 13:27:13.000
2009-06-10 13:27:34.000
2009-06-10 00:00:00.000
You can get it using
SELECT
convert(varchar, convert(datetime, date), 111)
+ ' ' + substring(time, 1, 2)
+ ':' + substring(time, 3, 2)
+ ':' + substring(time, 5, 2)
CREATE TABLE #Table
(
[date] VARCHAR(100),
[time] VARCHAR(100)
)
INSERT INTO #Table VALUES
('20090610','132713'),
('20090610','132734')
;WITH Bits_CTE
AS
(
SELECT
[Date],
[Time],
[hrs] = CONVERT(INT,SUBSTRING([Time], 1, 2)),
[mns] = CONVERT(INT,SUBSTRING([Time], 3, 2)),
[secs] = CONVERT(INT,SUBSTRING([Time], 5, 2))
FROM #Table
)
SELECT
[Date],
[Time],
DATEADD(HOUR,[hrs],
DATEADD(MINUTE,[mns],
DATEADD(SECOND,[secs],[Date])))
FROM Bits_CTE
CREATE FUNCTION [dbo].[DateTimeAdd]
(
#datepart date,
#timepart time
)
RETURNS datetime2
AS
BEGIN
RETURN DATEADD(dd, DATEDIFF(dd, 0, #datepart), CAST(#timepart AS datetime2));
END
Sorry - Missed the bit in your question about storing the date and time as varchars. You would therefore still need to convert these data itemsbefore using this function.

converting date from varchar to date

I am trying to change the date format of a column, the column is set as varchar column name date time. The problem is that i cannot actually change the data type because the data is automatically inputted by a PLC on the automation side. I need the date in a date or numeric value because when i run my queries i need to give the system a date range. I am trying to use substrings to work around this issue but am getting an error saying that the data type is out of range. here is the syntax of my query.
select cast(
(substring(datetime, 1, 4) + '-' +
SUBSTRING(DateTime, 5, 2) + '-' +
SUBSTRING(DateTime, 7, 2) + ' ' + '00:00:00.000') as dateTime) as "Date"
, ID1
, ID2
, diameter
, WeightTheoretical
, WeightActual
, StockType
from table1
where datetime is not null
and datetime <> ''
and datetime <> '0'
order by "Date", ID1;
Edit- the date format is as such 20120622:00:00:00:000
Assuming your date is with the format yyyymmdd, you can convert the varchar to datetime like this:
select convert(datetime, columname, 112)
It looks from your SQL that your date string is of the format YYYYMMDD
This should convert fine using either the CAST or CONVERT functions:
eg
SELECT CONVERT(datetime,'20120601')
SELECT CAST('20120601' as datetime)
both return the expected value as a datetime.
EDIT: Based on the supplied format you specified, I'd use the SubString to chop the supplied data down a bit:
eg
SELECT CONVERT(datetime,SUBSTRING('20120601',1,8))
Based on the format of your data in the table (20120622:00:00:00:000) you can do the following:
declare #date varchar(50)
set #date = '20120622:00:00:00:000'
select cast(left(#date, 8) as datetime)
or
select convert(datetime, left(#date, 8))
results:
2012-06-22 00:00:00.000