Converting varchar into a decimal - sql-server

How do I turn the values below on the left into the values in brackets? (SQL Server 2012)
50 (000.050)
100 (000.100)
1000 (001.000)
9999 (009.999)
20000 (020.000)

This seems to be rather easy... What have you tried yourself?
First of all: If these values are (integer) numbers, you should not store them in a string column. Any code can break easily, if there are non-numeric values among them...
You can try this:
DECLARE #mockup TABLE(ID INT IDENTITY,YourValue VARCHAR(100))
INSERT INTO #mockup VALUES('50'),('100'),('1000'),('9999'),('20000');
SELECT *
,CAST(YourValue AS DECIMAL(10,3))/1000 AS NewValue
,FORMAT(CAST(YourValue AS DECIMAL(10,3))/1000,'000.000') AS Formatted
FROM #mockup
Casting a string like "1000" to DECIMAL will get a number back. This number can be divided by 1000 to get the value needed.
If you need the format as provided, you can use FORMAT() on SQL-Server 2012+, but this function is known as rather slow... If this is important for you, search for other ways to format a number. There are many examples here on SO...

Related

Passing column/variable as binary value to convert function

I am manipulating a large value containing rows and columns values separated with ASCII row and column separators. The result is tabular data which I am inserting in SQL table.
Simple example to get the idea:
George|20;Ivan|15;Peter|10;
is transform to:
George 20
Ivan 15
Peter 10
and inserted in Users ([name], [age]) table.
Before insert, each value is converted to its column type using TRY_CONVERT function. The issue is this does not work as expected with VARBINARY data. For example (the second output is correct):
DECLARE #A NVARCHAR(1024) = '0xFE520676B1A1D93DABAB2319EEA03674F3632EAEEB163D1E88244F5EB1DE10EB';
SELECT TRY_CONVERT(VARBINARY(255), #A)
-- 0x300078004600450035003200300036003700360042003100410031004400390033004400410042004100420032003300310039004500450041003000330036003700340046003300360033003200450041004500450042003100360033004400310045003800380032003400340046003500450042003100440045003100300045004200
SELECT TRY_CONVERT(VARBINARY(255), 0xFE520676B1A1D93DABAB2319EEA03674F3632EAEEB163D1E88244F5EB1DE10EB)
-- 0xFE520676B1A1D93DABAB2319EEA03674F3632EAEEB163D1E88244F5EB1DE10EB
When the VARBINARY data is passed as string, the string is converting itself to VARBINARY. I need to pass the data without quotes, but how to do this when a column/variable of type string is passed?
I needed to use the style option of the TRY_CONVERT function.
DECLARE #A NVARCHAR(1024) = '0xFE520676B1A1D93DABAB2319EEA03674F3632EAEEB163D1E88244F5EB1DE10EB';
-- using style option 1
SELECT TRY_CONVERT(VARBINARY(255), #A, 1)
SELECT TRY_CONVERT(VARBINARY(255), 0xFE520676B1A1D93DABAB2319EEA03674F3632EAEEB163D1E88244F5EB1DE10EB)

Remove portion of string TSQL

I have a string of numbers that I need to trim a portion from using TSQL.
The string of numbers will always start with a 101 then it will have a set of 0's and a set of random numbers.
Example: 1010000123456
I need to trim the 101 and the set of zeros. This is probably simple but I'm having all kinds of issues because I don't have a specific character to reference to using a CHARINDEX and the possible combination of a 001 when the random numbers start that I need to keep is giving me issues using a PATINDEX with a SUBSTRING.
Remove the 101 in the string, Cast to big integer and then cast back to string.
select cast(cast(right('1010000123456', len('1010000123456')-3) as bigint) as varchar(20))
select cast(cast(right('1010000103456', len('1010000103456')-3) as bigint) as varchar(20))

SQL Server 2005 decimal field behaviour

Ive create a simple table with a field x of type decimal(28,15)
I run the following query to insert a value:
insert into testtable values (1234567890123)
when I do a select from testtable I, field x has a value of
1234567890123.000000000000000
Is there a way to specify (perhaps in the table design) that sql server should NOT store the zero's after the decimal if its not required? i.e. when doing a select the data will be returned as
1234567890123
Also why does insert into testtable values (12345678901234) give the following error :
Arithmetic overflow error converting numeric to data type numeric.
Also why does insert into testtable values (12345678901234) give the following error :
You specified a total width of 28 with 15 digits after decimal point. That leaves at most 13 digits before decimal point.
Is there a way to specify that sql server should NOT store the zero's after the decimal if its no required?
Strictly speaking, "decimal" is a fixed precision format and thus any number will occupy exactly the same space as any other number (see MSDN).
Try the below query . it works fine ...
select cast(1234567890123.000000000000000 as decimal)

SQL 'float' data type, when output as XML, causes undesired float result

You can try simply:
table1: has a column1 of type 'float'
instead of
SELECT column1 from Table1; gives values as seen in table.
Say this returns 15.1
However, if you try
Select column1 from Table1
FOR XML PATH('Table1'), Root('SomeRoot'), TYPE
returns: 1.510000000000000e+001
Has anyone seen this, and how was this fixed?
thanks in advance :)
This is what you get when you work with floating point numbers. You can try this though:
SELECT CONVERT(varchar(100), CAST(column1 AS decimal(38,2)))
you will just need to adjust the precision on the decimal to fit your needs.
Also assuming MSSQL, the str function might fit your needs (MSDN):
select str(column1, 3,1)
It's not necessary to convert the float value into a string to solve this problem.
Just convert the float value into a decimal or a numeric type, with the precision you want.
SELECT CAST(column1 AS decimal(38,2))
or
SELECT CAST(column1 AS numeric(18,5))
When then number will be parsed in XML by Sql Server, it won't be in an exponential form.
This approach is obviously faster than a string conversion (that would occur twice).

Problem convert column values from VARCHAR(n) to DECIMAL

I have a SQL Server 2000 database with a column of type VARCHAR(255). All the data is either NULL, or numeric data with up to two points of precision (e.g. '11.85'). I tried to run the following T-SQL query but received the error 'Error converting data type varchar to numeric'
SELECT CAST([MyColumn] AS DECIMAL)
FROM [MyTable];
I tried a more specific cast, which also failed.
SELECT CAST([MyColumn] AS DECIMAL(6,2))
FROM [MyTable];
I also tried the following to see if any data is non-numeric, and the only values returned were NULL.
SELECT ISNUMERIC([MyColumn]), [MyColumn]
FROM [MyTable]
WHERE ISNUMERIC([MyColumn]) = 0;
I tried to convert to other data types, such as FLOAT and MONEY, but only MONEY was successful. So I tried the following:
SELECT CAST(CAST([MyColumn] AS MONEY) AS DECIMAL)
FROM [MyTable];
...which worked just fine. Any ideas why the original query failed? Will there be a problem if I first convert to MONEY and then to DECIMAL?
Thanks!
It's likely that this depends on whether the decimal symbol is a comma or a dot. Here are some test queries and their results:
select CAST('3.6' as decimal) -- 3.60
select CAST('3,6' as decimal) -- Error converting data type varchar to numeric.
select CAST('3.6' as money) -- 3.60
select CAST('3,6' as money) -- 36.00 (!)
select ISNUMERIC('3.6') -- 1
select ISNUMERIC('3,6') -- 1
The documentation for ISNUMERIC says :
ISNUMERIC returns 1 when the input
expression evaluates to a valid
integer, floating point number, money
or decimal type; otherwise it returns
0
Both 3.6 and 3,6 can be cast to money, so that's why isnumeric('3,6') returns 1.
To resolve this issue, replace the comma's with dots (or vice versa, if your system uses comma as the decimal symbol):
select cast(replace('3,6',',','.') as decimal)
Another option is to change the "decimal symbol" in Windows. It's in Config Panel -> Regional and Language -> Formats -> Additional Settings -> Numbers.
Another cause is empty strings. For example, if you use the import wizard to import a CSV file, empty fields will become empty strings, not nulls.
This is a common idiom for fixing this:
CAST(NULLIF([number_as_a_string],'') AS decimal(13,2))
Select CAST(isnull(MyColumn,0) as Decimal(4,2))
FROM [MyTable];

Resources