SQL, How to convert VARCHAR to bigint? - sql

I have a field that is VARCHAR(6) I am trying to insert it into another table of type bigint it is giving me an error
(Error Converting from data type varchar to bigint
here is what i am doing
CONVERT(bigint, seconds) as seconds
Can anybody help with this issue?

This is the answer
(CASE
WHEN
(isnumeric(ts.TimeInSeconds) = 1)
THEN
CAST(ts.TimeInSeconds AS bigint)
ELSE
0
END) AS seconds

an alternative would be to do something like:
SELECT
CAST(P0.seconds as bigint) as seconds
FROM
(
SELECT
seconds
FROM
TableName
WHERE
ISNUMERIC(seconds) = 1
) P0

I think your code is right. If you run the following code it converts the string '60' which is treated as varchar and it returns integer 60, if there is integer containing string in second it works.
select CONVERT(bigint,'60') as seconds
and it returns
60

Related

Converting decimal to Date

I have a column with dates formatted as decimals, for example: 20,210,830.
I want to convert this number to date format as 08/30/2021
I have tried to use convert and the database shoots me an error that convert is not a valid function. Cast seems to work but, only returns a null value every time.
This statement will validate:
SELECT CAST(CAST(CONTCLMPDTE AS VARCHAR(8)) AS DATE)
FROM CMSFIL.JCTDSC AS COMPLDATE
This statement works but, just outputs null. For background I am querying from a Db2 database.
My ultimate goal is to use this converted date to grab the difference from the current day.
Such as
DAY(CURRENT_DATE) - DAY(COMPLDATE)
Converting it to a date, you cqan do it like this
CREATE TABLE JCTDSC (
CONTCLMPDTE varchar(10)
);
INSERT INTO JCTDSC VALUES ('20,220,830')
SELECT date(to_date(REPLACE(CONTCLMPDTE,',',''),'YYYYMMDD')) FROM JCTDSC AS COMPLDATE
1
2022-08-30
fiddle
So after a long couple days and almost pulling my hair out, here is what worked for me.
SELECT date(substr(CONTCLMPDTE,1,4)||'-'||substr(CONTCLMPDTE,5,2)||'-'||substr(CONTCLMPDTE,7,2)) FROM JCTDSC WHERE COMPANYNUMBER={Company Number} AND JOBNUMBER={Job Number} LIMIT 1
This formatted from yyyymmdd to mm/dd/yyyy. It also worked for finding the days between current_date and CONTCLMPDTE using this code.
DAYS(CURRENT_DATE) - DAYS({COntract Compl Date Formatted})
Thank you all for your help!
You probably get an error because you have some INT / DECIMAL value which can't be converted to a date using this pattern.
The solution is to create some "safe" conversion function "eating" errors like below.
CREATE FUNCTION DATE_SAFE (P_DT INT)
RETURNS DATE
CONTAINS SQL
NO EXTERNAL ACTION
DETERMINISTIC
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
RETURN CAST (NULL AS DATE);
END;
RETURN DATE (TO_DATE (CAST (P_DT AS CHAR (8)), 'YYYYMMDD'));
END
Usage:
SELECT
CONTCLMPDTE
--, DATE (TO_DATE (CAST (CONTCLMPDTE AS CHAR (8)), 'YYYYMMDD'))
, DATE_SAFE (CONTCLMPDTE)
FROM (VALUES 0, 20220830) T (CONTCLMPDTE)
The function returns NULL if the corresponding INT can't be converted to a DATE, and no error is thrown as in case, when you uncomment the commented out line with built-in functions only.
The value just need to be converted into a string with a date format. Then you can use the date() function to convert to date.
create table qtemp/dec_vals (
col1 decimal(8,0) );
insert into qtemp/dec_vals
values (20200830), (20200831), (20200901), (20200902), (20200903), (20200904), (20200905), (20200906);
select date(substr(char(col1), 5, 2) || '/' || substr(char(col1), 7, 2) || '/' || substr(char(col1), 1, 4)) from qtemp/dec_vals;

how to get to_epoch(sysdate-90) in Hive

I have a query which runs good in Oracle, but i want to use the same query in Hive.
query:
select count(mem_id)
from mem
where cobrand_id = '10001372'
and user_type_id =1
and status_ind <>3
and LAST_ACCESSED >= to_epoch(sysdate-90);
Also, I have LAST_ACCESSED coulmn in double.example value of LAST_ACCEESSED is : 1.554386487E9, not sure what value this is i am guessing this could be seconds.
tried:
UNIX_TIMESTAMP( string date, string pattern )
FROM_UNIXTIME( bigint number_of_seconds [, string format] )
No luck. Can someone help me. Thanks in advance.
It seems 1.554386487E9 is the same unix epoch time stored in double, displayed in engineering notation, and it can be casted to BIGINT.
Checking your example:
select from_unixtime(cast(1.554386487E9 as bigint));
OK
2019-04-04 07:01:27
Does this timestamp look good?
If yes, then use unix_timestamp(concat(date_sub(current_date,90),' 00:00:00')) to get epoch time for current date - 90 days.
Your query fixed:
select count(mem_id)
from mem
where cobrand_id = '10001372'
and user_type_id =1
and status_ind <>3
and cast(LAST_ACCESSED as BIGINT) >= unix_timestamp(concat(date_sub(current_date,90),' 00:00:00'))

SQL convert single int to a time value

I am trying to convert a single integer which represents the hour value into a time. I've tried using cast but this converts the value to a date
cast(datepart(hh,tstart) as datetime) as test
I've also tried casting it as a time and the conversion is not allowed.
The numbers I am working with are 7,8,9,10,11,12,13,...,23, 0
The format I would like is convert 7 to 7:00, 23 to 23:00, etc
Thank you
There are many ways to do that:
WITH table_name AS
(
SELECT * FROM (VALUES
(1),(2),(3),(10),(23)
) T(H)
)
SELECT DATEADD(HOUR, H, 0) DateValue,
CONVERT(time, DATEADD(HOUR, H, 0)) TimeValue,
CONVERT(varchar(2), H)+':00' TextValue
FROM table_name T1
I would recomend storing value as TIME datatype.
You can try this:
select cast(dateadd(hour,3,'00:00:00') as time)
which gives result:
03:00:00.0000000
Use your int values in place of 3 in above statement
Use convert datetime to varchar datatype and use case statement
DECLARE #date datetime ='2016-05-01 10:00:000'
SELECT CASE cast(DATEPART(hh,#date)as varchar(10))
WHEN '10'then '10:00'
WHEN '11'then '11:00'
WHEN '12'then '12:00'
.
.
.
WHEN '23' then '23:00'
END 'Hourpart'
You can concatenate a minute to the time and cast it to time
select cast(concat(20,':00') as time(7)) as 'time'
If you wanted to display like 'HH:MM',use the below query.
SELECT CAST(23 AS VARCHAR(50))+':00'
If you wanted to get the result as time format,use the below query.
SELECT CAST(CAST(23 AS VARCHAR(50))+':00:00' AS TIME)
OR
SELECT CAST(DATEADD(HOUR,23,'00:00:00') as time)
here is the sample output :
Assuming all of your potential values are integers between 1 and 24, I think FORMAT is the simplest way.
FORMAT(tstart*100,'00:00')

SQL Select range for nvarchar column

How do I select from tables where the column_a in range 55 - 42000.
Note : column_a's datatype is in nvarchar
I have try like this, but no luck
SELECT
SoftwareName, SoftwareImageTeaser, SoftwarePrice, SoftwareDescription
FROM
View_Software_Listing_With_Category
WHERE
(SoftwarePrice >= '55' AND SoftwarePrice <= '42000')
SELECT SoftwareName,SoftwareImageTeaser,SoftwarePrice,SoftwareDescription
FROM View_Software_Listing_With_Category
WHERE (CAST(CAST(SoftwarePrice AS FLOAT) AS INT) BETWEEN 55 AND 42000
Try this,As your SoftwarePrice column is nvarchar, you need to convert it in Integer for comparing with integer values. Then you can use between clause for filtering records.
SELECT SoftwareName,SoftwareImageTeaser,SoftwarePrice,SoftwareDescription
FROM View_Software_Listing_With_Category
WHERE Cast(SoftwarePrice as Int) between 55 AND 42000

tSQL - Conversion from varchar to numeric works for all but integer

I have a table with numbers in a varchar(255) field. They're all greater than one and have multiple decimal places. I'd like to convert them to integers. According to every web site I've consulted, including this one on StackOverflow, either of these should work:
SELECT CAST(VarcharCol AS INT) FROM MyTable
SELECT CONVERT(INT, VarcharCol) FROM MyTable
These both work for me for every kind of numeric value but integer - I can convert to float, decimal, etc. just fine, but trying to convert to integer gives me the following error:
Conversion failed when converting the varchar value '7082.7758172'
to data type int.
I've worked around the problem by converting to data type Decimal(6,0), which works fine. But just for my education, can anyone tell me why converting to data type int (or integer) gives me an error? Thanks.
Converting a varchar value into an int fails when the value includes a decimal point to prevent loss of data.
If you convert to a decimal or float value first, then convert to int, the conversion works.
Either example below will return 7082:
SELECT CONVERT(int, CONVERT(decimal(12,7), '7082.7758172'));
SELECT CAST(CAST('7082.7758172' as float) as int);
Be aware that converting to a float value may result, in rare circumstances, in a loss of precision. I would tend towards using a decimal value, however you'll need to specify precision and scale values that make sense for the varchar data you're converting.
Actually whether there are digits or not is irrelevant. The . (dot) is forbidden if you want to cast to int. Dot can't - logically - be part of Integer definition, so even:
select cast ('7.0' as int)
select cast ('7.' as int)
will fail but both are fine for floats.
Presumably, you want to convert values before the decimal place to an integer. If so, use case and check for the right format:
SELECT (case when varcharcol not like '%.%' then cast(varcharcol as int)
else cast(left(varcharcol, chardindex('.', varcharcol) - 1) as int)
end) IntVal
FROM MyTable;
Try this
declare #v varchar(20)
set #v = 'Number'
select case when isnumeric(#v) = 1 then #v
else #v end
and
declare #v varchar(20)
set #v = '7082.7758172'
select case when isnumeric(#v) = 1 then #v
else convert(numeric(18,0),#v) end
Try this query:
SELECT cast(column_name as type) as col_identifier FROM tableName WHERE 1=1
Before comparing, the cast function will convert varchar type value to integer type.
SELECT
convert(numeric(18,5),Col1), Col2
FROM DBname.dbo.TableName
WHERE isnumeric(isnull(Col1,1)) <> 0