conversion varchar to int issues - sql

The following query attempts to convert a varchar datatype to int -- but it's not working. Do you know why?
SELECT
CONVERT(INT, [BR]) AS dd,
CAST([BR] AS INT) AS cc
FROM
[Seg].[dbo].[pro_ben]
I get the error:
Msg 245, Level 16, State 1, Line 2
Conversion failed when converting the varchar value '3893.768' to data type int

Obviously your string has a decimal part, hence you cannot cast it directly to an integer.
A solution would be to first CAST to a floating point number, and then to an integer, like:
SELECT CAST( CAST([BR] AS FLOAT) AS INT) AS CC FROM [Seg].[dbo].[pro_ben]
Demo on DB Fiddle:
SELECT CAST('3893.768' AS FLOAT)
| (No column name) |
| ---------------: |
| 3893.768 |
SELECT CAST( CAST('3893.768' AS FLOAT) AS INT)
| (No column name) |
| ---------------: |
| 3893 |

The value is not an integer. This leaves you with various options:
You could use try_convert() which would return NULL.
You can use an intermediate data type and then convert to the final data type, but you might lose precision (under some circumstances).
You could convert to a numeric() instead.
Conversion to a numeric ignores decimal points, but they do not cause an error:
SELECT convert(numeric(10,0), [BR]) as dd
FROM [Seg].[dbo].[pro_ben];
You can then convert to an int if you specifically need that type.

I would try
Select Round([BR],0) as dd
FROM [Seg].[dbo].[pro_ben];

mmmm it appears once I change data type to float, it works.

Related

SQL - Insert Into - Convert Datatype

my table consists of the following fields:
IDTemp int NO NULL
Nr_ nvarchar(50) NULL
Description nvarchar(50) NULL
[Description 2] nvarchar(50) NULL
Price money NULL
Now I want to insert some values into that table from another database, unfortunately the price values from the other database are stored as a nvarchar and not a money value.
It looks a bit like this: 49.0000000000
If I insert this value into my money field, it stays empty.
My question is, how can I use INSERT INTO and convert my price value so that it goes into my money field and doesn't have 10 zeroes?
INSERT INTO TempSaveArticle (Nr_, Description, [Description 2], Price)
VALUES (123456789, Yarn, blue, '49.0000000000')
Thanks for your help in advance
Use CONVERT().
INSERT INTO TempSaveArticle (Nr_, Description, [Description 2], Price)
VALUES (123456789, Yarn, blue, CONVERT(MONEY, 49.0000000000))
Ideally you'd want to do this more dynamically.
INSERT INTO TempSaveArticle (Nr_, Description, [Description 2], Price)
SELECT myTable.*
FROM myTable
WHERE myTable.ID = 123 OR <<some other conditions>>
MONEY is effectively a DECIMAL.
You can CAST() or CONVERT() it to and from Decimal <--> Money. The only difference I know, is that MONEY is displayed by default using your computers' Language settings. But in my opinion, don't use MONEY, stick with DECIMALS and display it how you want using FORMAT(). More on this argument here.
use CAST to convert this properly
SELECT CAST ('49.0000000000' as numeric(10,2));
output :
49.00
We have to use cast or convert, this works directly for datatype CHAR, VARCHAR, NCHAR and NVARCHAR.
SQL server will not convert directly from TEXT to money. If the datatype is TEXT we have to first cast to varchar(for example) and then cast again to money.
NB: In some countries, for example France where I leave, it is standard practise to use a comma instead of a point. If there is a possibility of this we would need to use REPLACE first otherwise we will get an error.
create table mon (
monet text, monev nvarchar(20),
monetm money, monevm money);
GO
✓
insert into mon (monet, monev) values('49.0000000000','49.0000000000');
GO
1 rows affected
select * from mon;
GO
monet | monev | monetm | monevm
:------------ | :------------ | -----: | -----:
49.0000000000 | 49.0000000000 | null | null
update mon set monevm = cast(monev as decimal(20,10))from mon;
GO
1 rows affected
update mon set monetm = cast(monet as decimal(20,10))from mon;
GO
Msg 529 Level 16 State 2 Line 1
Explicit conversion from data type text to decimal is not allowed.
update mon set monetm = cast(
cast(monet as varchar)
as decimal(20,10))from mon;
GO
1 rows affected
select * from mon;
GO
monet | monev | monetm | monevm
:------------ | :------------ | ------: | ------:
49.0000000000 | 49.0000000000 | 49.0000 | 49.0000
db<>fiddle here

query varchar field with date values

on sql-server db i need to query the dates > getdate from a varchar field
My table is like below ( activatioDate type is varchar(100)) :
id | activatioDate
22 | 12/3/2021
23 | 12/7/2019
24 | 12/9/2020
25 | 12/3/2019
26 | 12/11/2019
27 | 12/1/2024
my query
select * from mytable
where activatioDate > GETDATE()
Expected result
22 | 12/3/2021
24 | 12/9/2020
27 | 12/1/2024
I've got the following error
"The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. "
Any suggestion?
You need to fix your design; that's the real problem here. Firstly, change the values to a unambiguous date/time format:
UPDATE dbo.YourTable
SET activatioDate = CONVERT(varchar(8),CONVERT(date,activatioDate,101),120);
Then you can ALTER the table:
ALTER dbo.YourTable ALTER COLUMN activatioDate date;
And then, finally, your query will work:
SELECT *
FROM dbo.YourTable
WHERE activatioDate > GETDATE();
Use CONVERT:
SELECT *
FROM mytable
WHERE CONVERT(datetime, activatioDate, 101) > GETDATE();
But in general you should avoid storing your dates as text in your SQL database.
Find all employees who didn't make any orders in the past 6 months. Tricky thing - the date field is varchar. You need to cast it to Date and apply Date functions

Convert from text(char(50)) to datetime

I'm trying to convert my text column to a datetime. I've tried several things but i keep getting errors. The steps I tried so far:
Convert(datetime, mydate, 103)
The error it gives after performing this query in my system:
'Arithmetic overflow error converting expression to data type datetime'
So I searched on the internet and found several solutions which I tried.
Convert(datetime, convert(char(8), mydate)
and
Cast(cast(mydate as char(8)) as datetime)
The error it gives me after performing these queries: 'conversion failed when converting date and/or time from character string' So I searched for more possible solutions and tried this:
Convert(datetime, convert(char(8), mydate),103)
But this still gives me the same error. I really run out of solutions right now. Does any of you guys maybe know how to fix this problem?
Kind regards and thanks in advance
Here is some sample data:
+----+------------+
| ID | MyDate |
+----+------------+
| 1 | 20170120 |
+----+------------+
| 2 | 19940101 |
+----+------------+
| 3 | 20001220 |
+----+------------+
| 4 | 20171101 |
+----+------------+
The issue is likely with formatting. Do you have an example of the string you're trying to convert to a datetime?
I would advise referring to the "style" parameter in the documentation to ensure it matches the string format that you're passing into the CONVERT function. If you can provide a sample string it will be easier to suggest a working example.
https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-2017
#miltenburger, I am guessing that #mydate has been stored as integer. That is why it throws the error:
Msg 8115, Level 16, State 2, Line 4
Arithmetic overflow error converting expression to data type datetime
What you need to do is to convert it to varchar first before converting to datetime.
See the mockup below:
DECLARE #mydate INT =20181001
SELECT CONVERT(DATETIME, CAST(#mydate as VARCHAR(20)), 103)
You need to check the database Implied DATEFORMAT set by language
SET LANGUAGE us_english
SELECT CAST('2018-02-25' AS datetime)
SET LANGUAGE british
SELECT CAST('2018-02-25' AS datetime)
You have the wrong format
select convert(datetime, '20000113', 112)

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

MS SQL numeric data type and convertion with removing zero

create table test_int
(
num bigint
)
insert into test_int (num)
values (4096);
My task is to calculate 4096/1024/1024 and get decimal answer. Ok, int doesn't store values after dot, so:
select CAST (num as decimal)/1024/1024 AS decimal, ROUND ((CAST (num as decimal)/1024/1024),4,1) AS numeric from test_int
First one is pure resault, second one is after rounding:
decimal numeric
0.00390625000 0.00390000000
The task is to remove empty zeroes after values.
select convert(decimal(25,5), 4096/1024/1024 ,0)
returns 0.00000.
So how can I get 0.0039 instead of 0.00390000000?
Thanks in advance for any kind of help.
Cast the result to FLOAT.
Query
SELECT
CAST
(
CAST(num as decimal)/1024/1024
AS FLOAT
) AS decimal,
CAST
(
ROUND((CAST (num as decimal)/1024/1024),4,1)
AS FLOAT
) AS numeric
from test_int;
Result
+---------------+---------------+
| decimal | numeric |
+---------------+---------------+
| 0.00390625 | 0.0039 |
+---------------+---------------+
SQL Fiddle
This one will work , but if i'm not mistaken , this will only work for 2008 version and above.
SELECT CONVERT(DOUBLE PRECISION, 0.00390000000)
result: 0.0039