cast an integer converted to varchar and appended with a string to a datetime - sql

I can't figure out why this sql code snippet does not work:
cast(cast(b.remodelyear as varchar(5)) + '-01-01' as datetime)
Remodel year is an integer consisting of a year (ex: 2012). I cast it to varchar and append a month and a day to it and then I cast the whole thing to a datetime.
This one works:
cast(cast(Yr as varchar(5)) + '-' + cast(Mth as varchar(5)) + '-' + '01' as datetime)
Where did I go wrong?
Thanks!

Personally, I wouldn't concatenate strings for this, I'd perform some (trivial) date math:
SELECT DATEADD(year, b.remodelyear - 1, '00010101')
FROM <sometable> b
(note that I'm assuming SQL Server - read this blog post for the reasoning behind the date format. If you're using a different RDBMS this'll need to be translated).
I'm curious as to why you're casting to varchar(5), as pretty much every RDBMS I'm aware of would throw an error if it encountered a fifth digit.

Related

Change the numeric format into 'AM/PM' format in CONCAT / MAX (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...

SQL Server: convert and merge separate date and time columns (both integers)

I am working on a query, where I have to fill a table's column ([Result_DateTime]) with datetime values.
The datetime based on two columns, both integer. One contains the date and the other is the time, as it is.
As you can see from the picture, it is a bit difficult to merge and convert these values to an actual datetime, because of the way they are stored. Mainly the time value causing problems.
I concluded how to convert the date column:
CONVERT(DATETIME, LEFT(20200131, 8))
but then I got stuck - what to do with the time and how to merge the two into one datetime effectively?
Using function STUFF looks nasty...
Could you help me out please? I am using SQL Server 2014
Below is one method to do it:
SELECT CAST(Convert(DATE, LEFT(DATEUPDT, 8)) AS VARCHAR(10)) +' '+CAST (TIMEUPDT/100 AS VARCHAR(4)) + ':' + CAST(TIMEUPDT%(100 * (TIMEUPDT/100)) AS VARCHAR(10))+':00'
FROM TEST_TABLE_TIME;
I think I found one solution. What I tried is to avoid using varchar conversions because of how the time column's zeros are cut off. However, I am not convinced that this is the most effective way to do so:
DECLARE #DateInt int = 20200131
DECLARE #TimeInt int = 345 -- 03:45:00
SELECT CONVERT(DATETIME, LEFT(#DateInt, 8)) +
CAST(DATEADD(second, FLOOR(#TimeInt / 100) * 3600 + FLOOR(#TimeInt / 1) % 100 * 60, 0) as datetime)
I was testing it with various time values, it is working.

Hardcode a specific day in data time while pulling the data - SQL

Actually I have different date in SQL table when I pull those via SQL query, day of datetime field should have fixed day.
Example: (DD-MM-YYYY) day should be "7" > (7-MM-YYYY)
10-08-2007 > 07-08-2007
27-12-2013 > 07-12-2013
01-03-2017 > 07-03-2017
Can someone help me on this. Thanks in Advance.
Find the difference between 7 and the day of the original date and add that to the original date:
SELECT DATEADD(DAY, 7 - DAY(OriginalDate), OriginalDate)
Use DATEPART to take out the month and year parts. Cast those into varchar and concatenate with 07.
Query
select '07-' +
cast(DATEPART(mm, [date_column]) as varchar(2)) + '-' +
cast(DATEPART(yyyy, [date_column]) as varchar(4))
from your_table_name;
Assuming You might have to change the day number example
DECLARE #dayNum char(2)
SELECT #dayNum = '07'
select #dayNum + Right(convert(char(10),getdate(),105),8)
If that is not the case You could do this
select '07'+ Right(convert(char(10),'10-08-2007',105),8)
I'd go this way:
SELECT CONVERT(DATE,CONVERT(VARCHAR(6),GETDATE(),112)+'25',112);
CONVERT with format 112 will return the date as unseparated ISO (today we would get 20170407). Convert this to VARCHAR(6) will implicitly cut away the day's part (201704).
Now we add a day and use again CONVERT with 112, but now with DATE as target type.
One thing to keep in mind: The day you add must be two-digit. You can achieve this with
DECLARE #int INT=7;
SELECT REPLACE(STR(#int,2),' ','0');
Use DATEFROMPARTS: Updated ONLY works from 2012 - OP has tagged SQL-Server 2008
select DATEFROMPARTS ( year('10-08-2007'), month('10-08-2007'), 7 )
Assuming that your field is of datetime datatype and your fixed day is of integer type.
select datetimecolumn+(yourparamfixedday-datepart(dd,datetimecolumn))

Convert date format doesn't take effect on self made date string in SQL Server

I have a rather strange issue here. I have a date string, which I've created partly by myself to incorporate a variable. The problem is, that I'm setting another language settings. In this case, I have to also convert the string to fit the language settings format. I'm using this code:
cast(convert(varchar, cast(cast(getdate() as date) as varchar) + ' ' + RIGHT('0' + CAST(#HR as varchar), 2) + ':00:00.000', 120) as datetime)
I get the error "The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.", which is normal if you assign wrong date format before casting.
The problem is, that when I try to convert the personally created date string, it doesn't change its format no matter what format code I set it in. That doesn't change even when I hardcode a number instead of my variable:
convert(varchar, cast(cast(getdate() as date) as varchar) + ' 0' + CAST(2 as varchar) + ':00:00.000', 101)
results in 2016-09-14 02:00:00.000
For example,
convert(varchar, dateadd(Hour, 2, getdate()), 101) as datetime
Results in 09/14/2016.
Even though I have a different language setting, isn't SQL server supposed to always recognize the date format in the standard format?
Please give me an advice so I can overcome this issue.
Thanks in advance!
PS: I managed to solve my issue by inserting converted datetime column in a variable before setting bulgarian language. I'm still very interested to know what causes the problem though.
Ok I may have a soution for the question: Why is the format differently handled in SQL-SERVER when converting.
CONVERT(data_type(length),expression,style)
The STYLEvalue only applies for date/time.
So it's because of the datatype that the output is different.
See following example:
SELECT convert(varchar, dateadd(Hour, 2, getdate()), 101) as datetime
You get the result:
09/14/2016
Here your are converting a datetime datatype into a varchar and the STYLE-value with 101 applies for CONVERT and the output is converted in that format.
Example 2 is the same but the inner most part is casted into a varchar before converting it:
SELECT convert(varchar, CAST(dateadd(Hour, 2, getdate()) AS varchar), 101) as datetime
The result you get is:
Sep 14 2016 4:09PM
So because we are trying to convert a varchar into a varchar the STYLE-value doesn't apply for the conversion.
That is also why the first query is handled diffrent then the other:
SELECT convert(varchar, cast(cast(getdate() as date) as varchar) + ' 0' + CAST(2 as varchar) + ':00:00.000', 101)
Here you cast into varchar cast(cast(getdate() as date) as varchar) before converting. So the STYLE-value is not applying because it's not from datatype date/time.
I hope it made it a bit clear. Let me know if this helped.
When you use convert to format the datetime, you can pass a style number to it.
Looky here or here for those numbers.
The query below converts custom created datetimes to the 126 (ISO8601) format.
declare #d int = 2;
SELECT
CONVERT(varchar,
CONVERT(datetime,
CONCAT(FORMAT(GETDATE(),'yyyy-MM-dd'),' ',#d,':0')
)
,126) AS MyDateStamp1,
CONVERT(varchar,
CONVERT(datetime,
CONVERT(varchar,GETDATE(),102)+' '+convert(varchar,#d)+':0'
)
,126) AS MyDateStamp2;
The FORMAT & CONCAT functions can be used in SQL Server 2012 and beyond.
But if you have an earlier version then CONVERT should work instead.
Additional tip:
If you're using the CONVERT solution above, note that
"convert(varchar, CAST(dateadd(Hour, 2, getdate()) AS varchar), 101)" calls for you to set datatype to varchar.
I just came across code
"Convert(date,ML.StartDate,101)"
and since style 101 is mm/dd/yyyy, and the output was yyyy-mm-dd, I knew something was wrong. By changing the code to
"Convert(varchar,ML.StartDate,101)"
the proper date style was displayed in the result set.

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).