Is there a nicer way to convert NVARCHAR to INT on SQL Server?
SELECT CONVERT(INT, CONVERT(FLOAT, N'5.0'))
Why do simple CONVERT or CAST cause errors?
SELECT CONVERT(INT, N'5.0')
SELECT CAST(N'5.0 AS INT)
Why do simple CONVERT or CAST cause errors?
Because the value you are trying to convert has a decimal point. And integers don't have decimal points.
You can get around this using DECIMAL as well as floating point numbers:
SELECT CONVERT(decimal(10, 0), N'5.0')
DECIMAL accepts the decimal places (even more than 1) and rounds the value to the appropriate integer, so the result can be either larger or smaller than the input.
This has the same range as integer, so it is pretty equivalent -- and you can convert back:
SELECT CONVERT(int, CONVERT(decimal(10, 0), N'5.0'))
Note that these are still subject to overflow errors, so I recommend TRY_CONVERT().
You can combine try_convert and isnull functions together. try_convert will return null when it fails to convert. And isnull will use the fallback value if the first argument is null. But a good part of it it will use first arguments datatype so end result will be an int if use the below code :
declare #text nvarchar(20) = N'5.6'
select isnull(try_convert(int,#text),convert(float,#text))
Fiddle
Related
I have the following string and want to convert it to DECIMAL(38,0):
a321
The following code is OK:
SELECT CAST(CONVERT(binary(2), 'a321', 2) AS BIGINT); -- 41761
but this one fails:
SELECT CAST(CONVERT(binary(2), 'a321', 2) AS DECIMAL(38,0));
Msg 8114, Level 16, State 5, Line 7 Error converting data type
varbinary to numeric.
It is not a big deal to do two casts like this:
SELECT CAST(CAST(CONVERT(binary(2), 'a321', 2) AS BIGINT) AS DECIMAL(38,0));
but I want to know why is not working. Can anyone explain?
Convert to a bigint first and then convert to a decimal:
SELECT CONVERT(DECIMAL(38, 0), CONVERT(BIGINT, CONVERT(binary(2), 'a321', 2)))
The binary representation of decimals is quite different from integers, and not all binary representations can be converted to a decimal.
This may be because the number you are trying to convert is an integer, not a decimal.
SELECT CAST(41761 AS VARBINARY), CAST(41761.0 as VARBINARY)
The above give different results as I suspect that the later carries information about the decimal component. Likewise, when converting the decimal value to binary, it works as expected.
SELECT CAST(41761.0 as VARBINARY) -- gives 0x060100014A5F0600 on Azure SQL
SELECT CAST(0x060100014A5F0600 as DECIMAL) -- gives 41761 on Azure SQL
I have tagged the server in as MSDN states the results may very between versions.
Do not construct binary values, and then convert them to a data type of the numeric data type category. SQL Server does not guarantee that the result of a decimal or numeric data type conversion, to binary, will be the same between versions of SQL Server.
I have an issue with a varchar float number e.g 2.045.030 which needs to be converted to float from varchar.
When trying to use any of the try_parse, try_convert, try_cast functions I get NULL instead of the converted value.
This is on a SQL server database.
Did anyone have a similar issue?
It seems that the values are formatted with . as thousands separator (and , as decimal point), so remove the points and replace a comma by the decimal point:
DECLARE #num varchar(50) = '2.045.030,725';
SELECT CAST(REPLACE(REPLACE(#num, '.', ''), ',', '.') AS float);
Result: 2045030.725
I'm trying to convert a number to a decimal with two decimals places.
SELECT CONVERT(DECIMAL(10,2),12345)
The above would return 12345.00 but I'm trying to achieve 123.45
You need something like that:
SELECT CONVERT(DECIMAL(15,2),12345/100.0)
SELECT CONVERT(DECIMAL(10,2),CAST(12345 as float)/CAST(100 as float))
Correction: The premise is somewhat flawed, as the data type of a literal number without a decimal point is int, not numeric as implied by the question. In that case, you do need to convert the initial value to either numeric or decimal before dividing:
SELECT CONVERT(DECIMAL,12345)/100
or
SELECT CAST(12345 AS DECIMAL)/100
(cast is the SQL standard, so if you ever want to apply this to other databases, it would be the preferred method.)
Alternately, you can just add a decimal point to the divisor, as SQL server will return the more precise data type when doing arithmetic on heterogeneous types:
SELECT 12345/100.0
According to the documentation, the numeric data type is functionally equivalent to the decimal datatype, so there's really no reason to convert between the two. It seems that all you really want to do is divide the value you have by 100:
SELECT 12345/100
I am using Sybase and I am doing a select which returns me a column called "iftype", but its type is int and I need to convert into varchar. When I try to do the select without the convert function I get this error:
Error code 257, SQL state 37000: Implicit conversion from datatype 'VARCHAR' to 'INT' is not allowed. Use the CONVERT function to run this query.
I dont know how to implement the function CONVERT. Can anyone help me, please ?
Use the convert function.
SELECT CONVERT(varchar(10), field_name) FROM table_name
Use the STR function:
SELECT STR(field_name) FROM table_name
Arguments
float_expression
Is an expression of approximate numeric (float) data type with a decimal point.
length
Is the total length. This includes decimal point, sign, digits, and spaces. The default is 10.
decimal
Is the number of places to the right of the decimal point. decimal must be less than or equal to 16. If decimal is more than 16 then the result is truncated to sixteen places to the right of the decimal point.
source: https://msdn.microsoft.com/en-us/library/ms189527.aspx
You can use CAST function:
SELECT CAST(your_column_name AS varchar(10)) FROM your_table_name
Actually you don't need to use STR Or Convert. Just select 'xxx'+LTRIM(ColumnName) does the job.
Possibly, LTRIM uses Convert or STR under the hood.
LTRIM also removes need for providing length. It seems to be working for integer or float without worry of truncation.
SELECT LTRIM(ColumnName) FROM TableName
also, LTRIM is better than STR as
SELECT STR(1234567890.123)
gives 1234567890
whereas
SELECT LTRIM(1234567890.123)
gives 1234567890.123
SELECT Cast(Cast([field_name] AS BIGINT) AS NVARCHAR(255))
FROM table_name
CONVERT(DATA_TYPE , Your_Column) is the syntax for CONVERT method in SQL. From this convert function we can convert the data of the Column which is on the right side of the comma (,) to the data type in the left side of the comma (,) Please see below example.
SELECT CONVERT (VARCHAR(10), ColumnName) FROM TableName
I've got a column in my database which contains a price, stored as a varchar(10). The format that I need to pull it out as has a comma, but no decimal. So, if the price is 1500.00121, it should come out as "1,500", with comma intact. So here is what I have so far:
CONVERT(varchar, CAST(p.Price1 AS money), 1)
This still has the decimal place to ".xx" in it. How can I remove the decimal and trailing numbers while retaining the comma?
Why not stored it in Decimal(10,2) datatype? It's much better than storing it in VARCHAR since you don't have extra casting to another datatype.
You can use CAST and ROUND function:
SELECT ROUND(CAST('1500.00121' AS DECIMAL(10,4)), 0, 1)
That's it. The CAST function converts datatype to another datatype. The ROUND function returns a numeric value, rounded to the specified length or precision.
The original syntax for ROUND is
ROUND ( numeric_expression , length [ ,function ] )
Where Function parameter is the type of operation to perform. Function must be tinyint, smallint, or int. When function is omitted or has a value of 0 (default), numeric_expression is rounded. When a value other than 0 is specified, numeric_expression is truncated.
SQLFiddle Demo
ROUND (MSDN)
Decimal (MSDN)
I hope it will work
declare #q money = 1500.123
select parsename(convert(varchar,convert(money,#q), 1),2)
No sql server on hand but Something like
Declare #correctlyTyped Money
Set #correctlyTyped = Convert(Money, SomeBadlyTypedField)
Select
Substring(#correctlyTyped,0,DataLength(#correctlyTyped) - CharIndex('.',#correctlyTyped ))
Convert it to money, then select everything up to the decimal point.
Note this is relying on the locale / collation of the data. In mainland Europe for instance, , is the decimal separator and . is the thousand separator.