Change the numeric format into 'AM/PM' format in CONCAT / MAX (sql) - sql

I need to change the numeric format into 'AM/PM' format in CONCAT function (I use SSMS v 18.5.1)
Here is my formula. RCLDTE - is a date and RCLTIM is time. I basically need to leave RCLDTE as it is and change the format of RCLTIM from numeric to date and convert to AM/PM format.
How the column looks right now
Format of RCLTIM - numeric
CONCAT(c.RCLDTE, ' & ', MAX(c.RCLTIM)) AS 'Date & Time',
When I tried to use CONVERT function as I tend to use, it raised an error.
CONCAT(c.RCLDTE, ' & ', CONVERT(varchar(15),CAST( MAX(c.RCLTIM) AS TIME),100))
Error
Explicit conversion from data type numeric to time is not allowed.

The number for the date can be concatenated to the number for the time stuffed with colons. So that it can be converted to a DATETIME.
And by using FORMAT the DATETIME can be put in a specific format.
(But use CONVERT if it has the format.)
Test snippet
declare #test table (
ID INT IDENTITY PRIMARY KEY,
RCLDTE int,
RCLTIM int
);
insert into #test (RCLDTE, RCLTIM) values
(20220119, 215250)
, (20220304, 070809)
;
select
FORMAT(TRY_CAST(CONCAT(c.RCLDTE, ' ', STUFF(STUFF(FORMAT(MAX(c.RCLTIM),'000000'),5,0,':'),3,0,':')) AS DATETIME)
, 'd/M/yyyy hh:mm:ss tt') AS [Date & Time]
from #test c
group by RCLDTE;
Date & Time
19/1/2022 09:52:50 PM
4/3/2022 07:08:09 AM
Test on db<>fiddle here

What you're attempting to do is very fragile, but I presume your source system gives you few options.
Converting like this has potential problems with DST & the language in use at the time of running.
Your question lost some of the detail regarding formats, so I can't see the time type you are using, but it looks like a decimal again.
Essentially, you need to put the the numerics in a string and then into datetime columns, but to get there you have to match a string conversion format the sqlserver.
Fortunately you are not far off the us format default.
Something like this will get you a date field, you can then amend the output format if you really need 12hr rather than 24hr.
SET LANGUAGE us_english
DECLARE #rcldte NUMERIC, #rcltim numeric
SET #rcldte=20220119
SET #rcltim = 015250
SELECT
CONVERT(DATETIME, CAST (#rcldte AS VARCHAR)+ ' ' +
LEFT( left('000000', 6-LEN(CAST ( #rcltim AS VARCHAR)))+CAST ( #rcltim AS VARCHAR),2)
+ ':' + substring( left('000000', 6-LEN(CAST ( #rcltim AS VARCHAR)))+CAST ( #rcltim AS VARCHAR),3,2)
+ ':' + RIGHT( left('000000', 6-LEN(CAST ( #rcltim AS VARCHAR)))+CAST ( #rcltim AS VARCHAR),2))
Which will give you:
(No column name)
2022-01-19 01:52:50.000
It's rather ugly though.
If you can guarantee the hours are zero padded then you could remove the complexity associated with that.
And if you're really going to use it then split into proper UDFs...

DECLARE #RCLDTE CHAR(8) = '20220119';
DECLARE #RCLTIM CHAR(6) = '215250';
select CONVERT(VARCHAR(21), (cast(#RCLDTE as DATETIME) + cast(substring(#RCLTIM,1,2)+':'+substring(#RCLTIM,3,2)+':'+substring(#RCLTIM,5,2) as DATEtime) ), 22);
output: 01/19/22 9:52:60 PM
For different formats of the DATETIME, see the docs of the CONVERT function:
https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver15
NOTE: When specifying another format the value 21 in VARCHAR(21) might need a change...

Related

Convert a string ddmmyyyyhhmi into yyyy-mm-dd in SQL server

how can I convert a string ddmmyyyyhhmi into yyyy-mm-dd?
A string 210420161701 (a varchar) into 2016-04-21 (a datetime data type).
I tried a combination of sub-string, cast, convert but can't seem to make it work.
Please kindly help thanks.
The first 2 lines are just setting up the variable, but the following works (as long as the format is always the same). You may also need to make sure the date format of your SQL installation is correct (SET DATEFORMAT). You can also change the datatype from date to datetime if required.
DECLARE #Date Varchar(100) = '210420161701'
DECLARE #DateVariable date
SELECT #DateVariable = SUBSTRING(#date,5,4) + '-' + SUBSTRING(#date,3,2) + '-' + SUBSTRING(#date,1,2)
SELECT #DateVariable
select
SUBSTRING(convert(varchar(10),'210420161701',103),5,4)+ '-'+
SUBSTRING(convert(varchar(10),'210420161701',103),3,2)+'-'+
SUBSTRING(convert(varchar(10),'210420161701',103),1,2)

How to store hour datepart in SQL in table

I have a table with 2 columns: Customer_ID, which is a string, identifying each client and Time_id: a string with 14 characters, identifying timestamp of a transaction. Example:
Customer_id; Time_id
12345; 20140703144504
I want to be able to use datediff in hours datepart, but I can´t seem to be able to convert time_id properly. I use the following query:
update transation_table
set time_id= (
convert(timestamp, time_id)
)
It works, but removes hours datepart, which is what I need. For day datepart I can do it, converting to datetime. How can I keep in the table the hh?
edit: I´m running MS SQL Server 2014.
best regards
Using the convert and string concatenation below, you can use DATEPART on the resulting value.
DECLARE #tmp TABLE(
Customer_id VARCHAR(50),
Time_id VARCHAR(50)
)
INSERT INTO #tmp
SELECT '12345','20140703144504'
select
*,CONVERT(DATETIME,
SUBSTRING(Time_id,5,2) + '/' +
SUBSTRING(Time_id,7,2) + '/' +
SUBSTRING(Time_id,1,4) + ' ' +
SUBSTRING(Time_id,9,2) + ':' +
SUBSTRING(Time_id,11,2) + ':' +
SUBSTRING(Time_id,13,2)
,101
)
from #tmp
Use FORMAT to get a string representation of the value in a supported format (ODBC canonical in the Date and Time styles chart), then use TRY_CONVERT to return an actual datetime value:
SELECT TRY_CONVERT(DATETIME,
FORMAT(CAST('20140703144504' AS BIGINT),
'####-##-## ##:##:##'),
120);
This requires SQL Server 2012+.
As mentioned elsewhere, the data should be stored in a single datetime2 column, or paired date and time columns. The above functions can be used to help convert existing data to the new column(s).

Char to DateTime Conversion

I have one column capturedatetime(Char(30)):
2006-04-25T15:50:59.997000 PM
And I want to convert it and load it at other table column which have is in DateTime. either by T-sql or SSIS which ever way.
I have tried with:
select CONVERT(datetime, '2006-04-25T15:50:59.997000 PM', 126)
But it creates an error:
Conversion failed when converting date and/or time from character string
Late update:
In this column I also have other data that is in a completely different format:
29-JAN-10 08.57.41.000000 PM
(1) STOP storing datetime data in string columns! This is nothing, nothing, nothing but trouble.
(2) Why on earth does your column get data in two different string formats that aren't even valid? Why does the string use 24 hour time and have AM/PM suffix? Why use a regional string format and Y2K disaster like 29-JAN-10?
Here is one way, but it's awfully ugly. I highly recommend you fix the SSIS process to give you valid datetime values in the first place, if not as datetimes, at least as valid ISO strings (yyyy-mm-ddThh:mm:ss.nnn):
DECLARE #x TABLE (d CHAR(30));
INSERT #x SELECT '2006-04-25T15:50:59.997000 PM'
UNION ALL SELECT '29-JAN-10 08.57.41.000000 PM';
SET LANGUAGE ENGLISH; -- this is important, else style 6 may not work
SELECT
CASE WHEN d LIKE '__[0-9]%' THEN
CONVERT(DATETIME, LEFT(d, 23))
WHEN d LIKE '[0-9][0-9]-%' THEN
CONVERT(DATETIME, CONVERT(CHAR(8),
CONVERT(DATETIME,REPLACE(LEFT(d,9),' ','-'),6),112)
+ ' ' + REPLACE(SUBSTRING(d,11,8),'.',':')
+ ' ' + RIGHT(RTRIM(d),2))
END
FROM #x;
The conversion for 126 requires no spaces ... I've got it to work like this:
declare #T varchar(50)
declare #dt datetime
set #T = '2006-04-25T15:50:59.997'
set #dt = convert(datetime,#t,126)
select #T, #dt
select convert(datetime,left('2006-04-25T15:50:59.997000 PM',23))
or
select convert(datetime,left(capturedatetime,23))
If you use cast, you do not even need to supply a format. Code snippet below tested on SQL 2012 Developer version.
declare #var_string varchar(50) = '2006-04-25T15:50:59.997';
declare #var_datetime datetime = cast(#var_string as datetime);
select #var_string as my_string, #var_datetime as my_variable;

Sql convert date format

I want to convert dateformat from mm/dd/yyyy to yyyy/mm/dd. I want the output in datetime format.
I tried this
convert(datetime,convert(varchar,getdate(),111),123)
but doesn't work. The error is "explicit conversion to datetime not available"
What is the best way to solve this problem? I'm using Sybase.
Try this
select convert(varchar,CAST('12/11/2010' as DateTime),111)
That won't work. The DATETIME data type has its own format that is really the amount of time that has passed since a fixed reference date; if you ask for a DATETIME it will always be returned according to that format.
How it is displayed to an end user is a function of the client. You can use CONVERT to convert it to a string and specify a format for how it is displayed in the string, but then you're returning a string, not a DATETIME. You can return it as a DATETIME (which has no inherent display format), and then it is up to the client application or OS to define how it is formatted for display. In client applications you also typically have formatting functions that display a date/time according to a format you specify. And if you haven't specified it explicitly in an application, then the display of the date/time will typically be defined by the localization settings in the OS.
Basically, there is a difference between the data type - DATETIME - and its representation to end users.
Formatting is something that should be done in the presentation tier not the data tier. However, most vendors, like Sybase, provide the ability to do rudimentary formatting:
Select Cast( Year(GetDate()) As char(4) )
+ '/' + Right( '00' + Cast( Month(GetDate()) As varchar(2) ), 2 )
+ '/' + Right( '00' + Cast( Day(GetDate()) As varchar(2) ), 2 )
Try this query
select (CONVERT(varchar(10), GETDATE(), 120))

T-SQL convert varchar yyyy-MM-dd-hh.mm.ss.nnnnnn into datetime

This is in MS SQL Server.
I have a varchar in the format yyyy-MM-dd-hh.mm.ss.nnnnnn
For example: 2010-09-17-20.52.31.870000
I want to convert this into a datetime... but ISDATE function in MSSQL says that is not a valid date and CONVERT won't work. Is there a way to use the convert function so that I can tell it what format the date is in?
I also want to check first that it is a valid date since the varchar input may contain nothing or it may contain an invalid date.
For example, invalid data of 2010-xx-r7-99.53esdfd.31.870000... I would skip that data and not even try to convert.
As far as I'm aware, SQL Server 2005 only supports milliseconds up to 3 digits, so you could replace the periods with colons, and grab the left and right portions (ignoring the hyphen between the day and hours) and come up with something like this:
DECLARE #myDate varchar(50)
SET #myDate = '2010-09-17-20.52.31.870000'
PRINT isdate(left(#myDate, 10) + ' ' +
replace(substring(#myDate, 12, 12), '.', ':')) -- Should print '1'
PRINT cast(left(#myDate, 10) + ' ' +
replace(substring(#myDate, 12, 12), '.', ':') as datetime)
... which will effectively give you 870 milliseconds
The ISO 8601 standard separates the date and time with the letter T. Maybe that's all it needs to convert successfully? Some conversion implementations accept a space there too. I've never seen a hyphen there.
You would have to change the punctuation a bit to make it work, and reduce the precision from microseconds to millisecond. This works:
convert(datetime, '2010-09-17 20:52:31.870', 121)
What you are getting in is a bit wonky, but this works (tested):
DECLARE #temp as varchar(50)
SET #temp = '2010-09-17-20.52.31.870'
SET #temp = replace(#temp,'.',':')
set #temp = stuff(#temp,11,1,'T')
set #temp = stuff(#temp,20,1,'.')
select #temp
select cast(#temp as datetime)
NB I cut off the extra 0s, you could do this with substring if there really are those extra ones.