How to convert round number to data and time format - sql

Two Column in table tblpress
Date Time
20160307 120949
20160307 133427
Need to be select below the format:
07-03-2016 12:09:49
07-03-2016 13:34 27
or
03-March-2016 12:09: 49 PM
03-March-2016 01:34: 27 PM

You can try below
select format(cast([Date] as date),'dd-MMMM-yyyy') as [Date],
TIMEFROMPARTS(LEFT([Time],2), SUBSTRING([Time],3,2), RIGHT([Time],2), 0,0) as [Time]

I think CAST/CONVERT will help you:
SELECT
CAST('20160307' AS date),
CAST(STUFF(STUFF('120949',3,0,':'),6,0,':') AS time)
And convert for out:
SELECT
CONVERT(varchar(20),NormalDate,105) OutDate, -- Italian style
CONVERT(varchar(20),NormalTime,108) OutTime -- hh:mi:ss
FROM
(
SELECT
CAST([Date] AS date) NormalDate,
CAST(STUFF(STUFF([Time],3,0,':'),6,0,':') AS time) NormalTime
FROM YourTable
) q
CAST and CONVERT (Transact-SQL)
And you can use FORMAT (Transact-SQL)
SELECT
FORMAT(GETDATE(),'dd-MM-yyyy'),
FORMAT(GETDATE(),'HH:mm:ss')

Best way to do it is to create a function :
create FUNCTION [dbo].[udfGetDateTimeFromInteger]
(
#intDate int,
#intTime int
)
RETURNS datetime
AS BEGIN
-- Declare the return variable here
DECLARE #DT_datetime datetime = NULL,
#str_date varchar(11),
#str_time varchar(8)
if(#intDate is not null and #intDate > 0)
begin
select #str_date = CAST( cast(#intDate as varchar(8)) AS date)
if #intTime=0
select #str_time ='000000'
else
select #str_time = right('0'+CONVERT(varchar(11),#intTime),6)
select #str_time =
SUBSTRING(#str_time,1,2)+':'+SUBSTRING(#str_time,3,2)+':'+SUBSTRING(#str_time,5,2)
select #DT_datetime = CAST(#str_date+' '+#str_time as datetime)
end
-- Return the result of the function
RETURN #DT_datetime
END
and then call it in select like :
declare #next_run_date int, #next_run_time int
select #next_run_date = 20160307
select #next_run_time = 130949
SELECT #next_run_date inputdate,
#next_run_time inputtime,
dbo.udfGetDateTimeFromInteger(#next_run_date, #next_run_time) outputdatetime
Output will be like :
inputdate inputtime outputdatetime
20160307 130949 2016-03-07 13:09:49.000

You said those are numbers, right? You can use datetimefromparts (or datetime2fromparts). ie:
select
datetimefromparts(
[date]/10000,
[date]%10000/100,
[date]%100,
[time]/10000,
[time]%10000/100,
[time]%100,0)
from tblpress;
DB Fiddle demo
Note that naming fields like that and also storing date and time like that is a bad idea.
I later noticed it was char fields:
select
cast([date] as datetime) +
cast(stuff(stuff([time],5,0,':'),3,0,':') as datetime)
from tblpress;

Related

How to cast and convert to datetime in where condition in t-sql?

I am trying to get last months worth of data from the table vis_p_activities_final and tried the query below:
SELECT * FROM DPICD.vis_p_activities_final
WHERE DPICD.vis_p_activities_final.current_activity_code IN (
'SDBPR', 'SDBPU', 'XSDBPU', 'SDBPUX' )
AND CAST((DPICD.vis_p_activities_final.raised_date_time) AS DATETIME) >=
Dateadd(month, -1, CURRENT_TIMESTAMP)`
the raised_date_time column is VARCHAR and I want to convert it to datetime for the filter. How can I do that?
you can use temp table as
declare #lastmonth datetime
set #lastmonth = Dateadd(month, -1, CURRENT_TIMESTAMP)`
SELECT *, CAST((DPICD.vis_p_activities_final.raised_date_time) AS DATETIME) as
'revised_date' into #tmp FROM DPICD.vis_p_activities_final
WHERE DPICD.vis_p_activities_final.current_activity_code IN (
'SDBPR', 'SDBPU', 'XSDBPU', 'SDBPUX' )
`
select * from #tmp where revised_date >= #lastmonth

Array like function for a statement

I have a statement that returns a single number for a date. What I want to do is to be able to execute the statement across a range of dates and get a value for each date.
select dbo.GetItemMTDIssues(inmastx.fac, inmastx.fpartno, inmastx.frev, '6-01-2019')
as MTDiss from inmastx where fpartno='ANF-10-6313-102'
This is how the results look for a single date that I'm getting with my current statement. 6-01-2019
|MTDiss|
600
This is the expected results that I want over a range of dates like 6-01-2019 - 6-05-2019
|MTDiss|
600
450
375
700
300
Also including the function if it's helpful.
CREATE FUNCTION [dbo].[GetItemMTDIssues]
(#fac char(20), #partno char(25), #rev char(3), #currentdate datetime)
returns numeric (15,5)
as
begin
declare #returnval as numeric (15,5)
set #returnval =
isnull(
(select sum(fQty)
from intran
where ftype = 'I'
and month(fdate) = month(#currentdate)
and year(fdate) = year(#currentdate)
and fac = #fac
and fpartno = #partno
and fcpartrev = #rev)
,0.0) * -1
return #returnval
end
You would need first to create the range, and the below t-sql will do that.
declare #startDate datetime='6-01-2019'
declare #endDate datetime='6-05-2019'
;with DateRange as (
select #startDate [date]
union all
select DATEADD(day,1,[date]) [date] from DateRange where [date]<#endDate
)
select * from DateRange
we can test it and see the result to confirm that this is the range we want.
note:if you need to jump by month or number of days other that go day by day you only need to change the code in the DATEADD.
Now we would need to update your function to take the start and end of the range and let it use all the range dates , I think something like the below will help:-
CREATE FUNCTION [GetItemMTDIssuesRange]
(
#fac char(20), #partno char(25), #rev char(3), #startDateRange datetime, #EndDateRange datetime
)
RETURNS TABLE
AS
RETURN
(
with DateRange as (
select #startDateRange [date]
union all
select DATEADD(day,1,[date]) [date] from DateRange where [date]<#EndDateRange
)
--select * from DateRange
select (isnull(sum(fQty),0.0) * -1) MTDiss
from intran
inner join DateRange on year(fdate) = year(DateRange.[date]) and month(fdate) = month(DateRange.[date])
where ftype = 'I'
and fac = #fac
and fpartno = #partno
and fcpartrev = #rev
group by DateRange.[date]
)
GO
Please check it.
if you dont want to change the function this below may help too:-
declare #startDate datetime='6-01-2019'
declare #endDate datetime='6-05-2019'
;with DateRange as (
select #startDate [date]
union all
select DATEADD(day,1,[date]) [date] from DateRange where [date]<#endDate
)
select dbo.GetItemMTDIssues(inmastx.fac, inmastx.fpartno, inmastx.frev, DateRange.[date])
as MTDiss from inmastx,DateRange
where fpartno='ANF-10-6313-102'

convert string to both date and time

I have a data where date and time comes up in yyyymmdd_time (20161012_1528) format.
I want to convert it to date time in SQL Server DB as 2016-10-12 15:28:00:00
is there any straight forward way to do this.or have to create a custom function?
Declare #String varchar(25) = '20161012_1528'
Select cast(left(#String,8)+' '+Stuff(right(#String,4),3,0,':') as datetime)
Or
Select cast(Stuff(Replace(#String,'_',' '),12,0,':') as datetime)
Returns
2016-10-12 15:28:00.000
Please try following method,
It requires a few datetime and convertion functions to be used
declare #dt datetime
declare #str varchar(40) = '20161012_1528'
select #dt =
DATEADD(MI, CAST(right(#str,2) as int),
DATEADD(hh, cast(SUBSTRING(#str,10,2) as int),
CONVERT(datetime, left(#str,8))
)
)
select #dt
The closest I could find was datetime format 112 which does not account for the "_hhmm". I would highly recommend just placing the convert into your T-SQL as the optimizer does not handle UDFs very well.
The T-SQL looks like:
DECLARE #datetimestring nvarchar(max) = '20161012_1528'
SELECT
dateadd(
minute,convert(
int,substring(
#datetimestring,charindex(
'_',#datetimestring
)+3,2
)
),dateadd(
hour,convert(
int,substring(
#datetimestring,charindex(
'_',#datetimestring
)+1,2
)
),convert(
datetime, substring(
#datetimestring,0,charindex(
'_',#datetimestring
)
), 112
)
)
)
The other option is to format the string to the expected date format which is shorter.
SELECT
convert(
datetime,replace(
stuff(
stuff(
stuff(
#datetimestring,5,0,'-'
),8,0,'-'
),14,0,':'
),'_',' '
)
)

How convert nvarchar column from a existing table to date? SQL Server

I have a table in SQL Server created like this:
CREATE TABLE nombres
(
nombre varchar (200) not null,
fecha_nac char (10) not null,
fecha_alta char (10) not null,
)
I created a stored procedure to fill the table quickly. The next step is "formatting" the dates made into date format. I saw that I can use
SELECT CONVERT(datetime, 'a string', 100)
In this case I want use my column as parameter like this
SELECT CONVERT (datetime, select fecha_nac from nombres, 100)
but I get an error.
I will be thankful if I get any help
DECLARE #site_value INT;
SET #site_value = 1;
WHILE #site_value <= (SELECT COUNT(nombre) FROM nombres)
BEGIN
WITH MyCte AS
(
SELECT fecha_nac,number= ROW_NUMBER() OVER (ORDER BY dbo.nombres.fecha_nac)
from dbo.nombres
)
SELECT convert(datetime,(SELECT MyCte.fecha_nac from MyCte WHERE number=#site_value), 101)
SET #site_value = #site_value + 1;
END;
With the date format you have, (mm-yyyy-dd), you can do some string manipulation to get it to dd-mm-yyyy and then it can be parsed as a DATE with format 103.
WITH cte AS (
SELECT '11-1994-27' fecha_nac
)
SELECT
CONVERT(DATE, SUBSTRING(fecha_nac, 9, 2) + '-' + SUBSTRING(fecha_nac, 0, 8), 103)
FROM cte;
-- 1994-11-27
Your fecha_alta format is easier, it can be parsed right away with format 102.
WITH cte AS (
SELECT '2012-1-12' fecha_alta UNION ALL
SELECT '1994-4-5'
)
SELECT
CONVERT(DATE, fecha_alta, 102)
FROM cte;
-- 2012-01-12
-- 1994-04-05

How do I create a datetime from a custom format string?

I have datetime values stored in a field as strings. They are stored as strings because that's how they come across the wire and the raw values are used in other places.
For reporting, I want to convert the custom format string (yyyymmddhhmm) to a datetime field in a view. My reports will use the view and work with real datetime values. This will make queries involving date ranges much easier.
How do I perform this conversion? I created the view but can't find a way to convert the string to a datetime.
Thanks!
Update 1 -
Here's the SQL I have so far. When I try to execute, I get a conversion error "Conversion failed when converting datetime from character string."
How do I handle nulls and datetime strings that are missing the time portion (just yyyymmdd)?
SELECT
dbo.PV1_B.PV1_F44_C1 AS ArrivalDT,
cast(substring(dbo.PV1_B.PV1_F44_C1, 1, 8)+' '+substring(dbo.PV1_B.PV1_F44_C1, 9, 2)+':'+substring(dbo.PV1_B.PV1_F44_C1, 11, 2) as datetime) AS ArrDT,
dbo.MSH_A.MSH_F9_C2 AS MessageType,
dbo.PID_A.PID_F3_C1 AS PRC,
dbo.PID_A.PID_F5_C1 AS LastName,
dbo.PID_A.PID_F5_C2 AS FirstName,
dbo.PID_A.PID_F5_C3 AS MiddleInitial,
dbo.PV1_A.PV1_F2_C1 AS Score,
dbo.MSH_A.MessageID AS MessageId
FROM dbo.MSH_A
INNER JOIN dbo.PID_A ON dbo.MSH_A.MessageID = dbo.PID_A.MessageID
INNER JOIN dbo.PV1_A ON dbo.MSH_A.MessageID = dbo.PV1_A.MessageID
INNER JOIN dbo.PV1_B ON dbo.MSH_A.MessageID = dbo.PV1_B.MessageID
According to here, there's no out-of-the-box CONVERT to get from your yyyymmddhhmm format to datetime.
Your strategy will be parsing the string to one of the formats provided on the documentation, then convert it.
declare #S varchar(12)
set #S = '201107062114'
select cast(substring(#S, 1, 8)+' '+substring(#S, 9, 2)+':'+substring(#S, 11, 2) as datetime)
Result:
2011-07-06 21:14:00.000'
This first changes your date string to 20110706 21:14. Date format yyyymmdd as a string is safe to convert to datetime in SQL Server regardless of SET DATEFORMAT setting.
Edit:
declare #T table(S varchar(12))
insert into #T values('201107062114')
insert into #T values('20110706')
insert into #T values(null)
select
case len(S)
when 12 then cast(substring(S, 1, 8)+' '+substring(S, 9, 2)+':'+substring(S, 11, 2) as datetime)
when 8 then cast(S as datetime)
end
from #T
Result:
2011-07-06 21:14:00.000
2011-07-06 00:00:00.000
NULL
You can use CAST or CONVERT.
Example from the site:
G. Using CAST and CONVERT with
datetime data
The following example displays the
current date and time, uses CAST to
change the current date and time to a
character data type, and then uses
CONVERT display the date and time in
the ISO 8901 format.
SELECT
GETDATE() AS UnconvertedDateTime,
CAST(GETDATE() AS nvarchar(30)) AS UsingCast,
CONVERT(nvarchar(30), GETDATE(), 126) AS UsingConvertTo_ISO8601;
GO
Here is the result set.
UnconvertedDateTime UsingCast UsingConvertTo_ISO8601
----------------------- ------------------------------ ------------------------------
2006-04-18 09:58:04.570 Apr 18 2006 9:58AM 2006-04-18T09:58:04.570
(1 row(s) affected)
Generally, you can use this code:
SELECT convert(datetime,'20110706',112)
If you need to force SQL Server to use a custom format string, use the following code:
SET DATEFORMAT ymd
SELECT convert(datetime,'20110706')
A one liner:
declare #datestring varchar(255)
set #datestring = '201102281723'
select convert(datetime, stuff(stuff(#datestring,9,0,' '),12,0,':') , 112 )
Result:
2011-02-28 17:23:00.000
DECLARE #d VARCHAR(12);
SET #d = '201101011235';
SELECT CONVERT(SMALLDATETIME, STUFF(STUFF(#d,9,0,' '),12,0,':'));
Note that by storing date/time data using an inappropriate data type, you cannot prevent bad data from ending up in here. So it might be safer to do this:
WITH x(d) AS
(
SELECT d = '201101011235'
UNION SELECT '201101011267' -- not valid
UNION SELECT NULL -- NULL
UNION SELECT '20110101' -- yyyymmdd only
),
y(d, dt) AS
(
SELECT d,
dt = STUFF(STUFF(LEFT(d+'000000',12),9,0,' '),12,0,':')
FROM x
)
SELECT CONVERT(SMALLDATETIME, dt), ''
FROM y
WHERE ISDATE(dt) = 1 OR d IS NULL
UNION
SELECT NULL, d
FROM y
WHERE ISDATE(dt) = 0 AND d IS NOT NULL;
DECLARE #test varchar(100) = '201104050800'
DECLARE #dt smalldatetime
SELECT #dt = SUBSTRING(#test, 5, 2)
+ '/' + SUBSTRING(#test, 7, 2) + '/'
+ SUBSTRING(#test, 1, 4) + ' ' + SUBSTRING(#test, 9, 2)
+ ':' + SUBSTRING(#test, 11, 2)
SELECT #dt
Output:
2011-04-05 08:00:00