Cast or convert varchar in SQL Server to INT - sql

I am trying to convert the following to an integer so that I can do calculations, from 123.456.789 to 123456789.
However, when I try
CAST([Total number] AS INT)
OR
CONVERT(int, [Total number])
then I get an error
Conversion failed when converting the varchar value '123.456.789' to data type int.

Declare #val varchar(100)='123.456.789'
SELECT CAST (REPLACE (#val,'.','') AS INT) As Intval

Assuming the dot is not a fractional part divider and your number is integer (not float/decimal) - you can just remove dots from your string prior to conversion something like:
CAST(replace([Total number], '.', '') AS int)

You can use try_convert or try_cast even if it has any special characters it will return null in that case
Select try_convert(int, replace([Total number], '.', ''))

Is this your requirement as below
Declare #val TABLE (ID INT IDENTITY,Val varchar(100))
INSERT INTO #val
SELECT '356.345.789' UNION ALL
SELECT '123.456.333' UNION ALL
SELECT '444.124.444' UNION ALL
SELECT '347.456.555' UNION ALL
SELECT '123.666.789' UNION ALL
SELECT '678.432.789' UNION ALL
SELECT '789.456.111' UNION ALL
SELECT '123.457.123' UNION ALL
SELECT '333.111.789'
SELECT ROW_NUMBER()OVER(Order by (SELECT 1)) AS Rno,
CAST(REPLACE (Val,'.','') AS INT) As Intval
FROM #val

Related

substract specific string from data sql

I am new to SQL
If I have a column like this
ID
00001234
00012345
00001235
00123456
I want to see a column of ID without '0' Like this
ID
1234
12345
1235
123456
How can I start? any advice?
In SQL Server you can use:
SELECT ID,
REPLACE(LTRIM(REPLACE(ID, '0', ' ') ), ' ', '0')
FROM mytable
The above can be easily adjusted to any other RDBMS you may use.
Cast it to Bigint and cast it back to varchar
Note:Assumption: RDBMS SQL SERVER, ID is of character type
SELECT * INTO #TAB FROM (
select '00001234' ID
UNION ALL
select '00012345'
UNION ALL
select '00001235'
UNION ALL
select '00123456'
)A
SELECT CAST(CAST(ID AS BIGINT) AS VARCHAR(50)) FROM #TAB

Implicit conversion between int and varchar

Below query show conversion error.
select 'a'
union all
select 1
to execute I have to explicitly convert it..
Is there any other way for implicit conversion?
may be we can convert integer to varchar explicitily.But in implicit we can convert alphabets to convert using ASCII values
select ASCII('a')
union all
select 1
or
select 'a'
union all
select CAST(1 AS VARCHAR)

Formatting a number as a monetary value including separators

I need some help with a sql transformation. This part of query that I have been provided with:
'$' + replace(cast((CAST(p.Price1 AS decimal(10,2)) * cast(isnull(p.Multiplier,1) as decimal(10,2))) as varchar), '.0000', '')
Basically, it ends up being a varchar that looks like this: $26980
I need to insert a comma at the thousand and million mark (if applicable). So in this instance, $26,980
What's the easiest way to do that without having to rewrite the whole thing?
Do it on the client side. Having said that, this example should show you the way.
with p(price1, multiplier) as (select 1234.5, 10)
select '$' + replace(cast((CAST(p.Price1 AS decimal(10,2)) * cast(isnull(p.Multiplier,1) as decimal(10,2))) as varchar), '.0000', ''),
'$' + parsename(convert(varchar,cast(p.price1*isnull(p.Multiplier,1) as money),1),2)
from p
The key is in the last expression
'$' + parsename(convert(varchar,cast(p.price1*isnull(p.Multiplier,1) as money),1),2)
Note: if p.price1 is of a higher precision than decimal(10,2), then you may have to cast it in the expression as well to produce a faithful translation since the original CAST(p.Priced1 as decimal(10,2)) will be performing rounding.
If you really must do it in TSQL you can use CONVERT(), but this sort of thing really doesn't belong in the database:
declare #m money = 12345678
-- with decimal places
select '$' + convert(varchar, #m, 1)
-- without decimal places
select '$' + replace(convert(varchar, #m, 1), '.00', '')
You could turn this into a function, it only goes 50 characters back.
DECLARE #input VARCHAR(50)
SELECT #input = '123123123.00'
SELECT #input = CASE WHEN CHARINDEX('.', #input) > offset +1
THEN STUFF(#input, CHARINDEX('.', #input) - offset, 0, ',')
ELSE #input END
FROM (SELECT 3 offset UNION SELECT 7 UNION SELECT 12 UNION SELECT 18 UNION SELECT 25 UNION SELECT 33 UNION SELECT 42) b
PRINT #input
The offset grows by +1 for each position, because it's assuming you've already inserted the commas for the previous positions.

how to convert string format

How can I convert a number to a formatted string of fixed length in SQL Server 2005 using T-SQL?
e.g.
Inputs: 5,01,007,0009,00011,01200
Result: 000005,000007,000009,0000011,001200
Looks like you want it 6 wide. Try putting your pad characters, in this case, zeros, to the left of your int/string, and then take the 6 chars on the right side of the string.
How about this?
DECLARE #i int;
SELECT #i = 1200;
SELECT RIGHT('000000'+ CAST(#i as varchar(10)), 6);
The best way I've found to do this is using the STR statement:
SELECT REPLACE(STR(123, 6), ' ', '0')
The above statement will result in 000123. It basically converts 123 to a string of 6 characters (padded with spaces), then uses REPLACE to replace the spaces with zeros.
TRY THIS
WITH t(c) AS
(
SELECT 1.99 UNION ALL
SELECT 21.34 UNION ALL
SELECT 1797.94 UNION ALL
SELECT 300.36 UNION ALL
SELECT 21.99 UNION ALL
SELECT -2.31
)
select
c,
replicate(0,4-len(replace(substring(cast(c as varchar(10)),1,charindex('.',c)-1),'-','')))+''+
replace(replace(substring(cast(c as varchar(10)),1,charindex('.',c)-1),'-',''),'','-') +''+
replace(substring(cast(c as varchar(10)),charindex('.',c),len(c)),'-','')
from t
i will still optimize it
Best way for dynamic leading zero allocation
WITH t(c) AS ( SELECT 1.99 UNION ALL
SELECT 21.34 UNION ALL SELECT
1797.94 UNION ALL SELECT 300.36 UNION ALL SELECT 21.99 UNION ALL
SELECT 2.31 ),
Final (a,b,c,d) as ( Select c,
substring(cast(c as
varchar(10)),1,charindex('.',c)-1) ,
(select max(len(substring(cast(c as
varchar(10)),1,charindex('.',c)-1)))
from t), substring(cast(c as
varchar(10)),charindex('.',c)+1,len(c))
From t group by c )
select a,
right(replicate('0',c)+''+b,4)+'.'+d
from final
declare #i int
set #i=10
print replace(str(#i),' ','0')

Select and filter nvarchar like a int

I have a nvarchar column BigMacs in table McTable in my MS SQL 2005 database with alfanumeric and numeric values. For example:
132
432adfad
sfs54543
5256
And now i would like to do something like this:
select Convert(BigMacs, int) from McTable
where IsNumerc(BigMacs) = 1 AND Convert(BigMacs, int) > 6
But when I do this i get a error:
Msg 245, Level 16, State 1, Line 41
Conversion failed when converting the nvarchar value '.' to data type int.
On line select.
How to fix this?
This is probably because the IsNumeric function returns true for any value that COULD be converted to a number. Try the following example:
create table McTable (BigMac varchar(255))
insert into McTable select '1p927'
insert into McTable select '1927'
insert into McTable select '1,927'
insert into McTable select '1.927'
select BigMac, isnumeric(BigMac)
from McTable
select BigMac, CAST(BigMac AS DECIMAL)
from McTable
where isnumeric(BigMac) = 1
Even though all rows except the '1p927' are numeric, the cast will fail! This is because '1,927' cannot be converted to a Decimal (on my machine)
IsNumeric doesn't work exactly as specified. As found here, you could use
IsNumeric (data + 'e0')
-Edo
Try this:
SELECT *
FROM (
SELECT REPLACE(BigMacs, ',', '.') AS BigMacs
FROM McTable m
WHERE IsNumerc(BigMacs) = 1
) q
WHERE CAST(BigMacs AS DECIMAL) > 6
IsNumeric will return TRUE on decimal fractions like 1234.1232, but they cannot be converted to INT.
Checking:
WITH McTable AS
(
SELECT '123124,123123' AS BigMacs
)
SELECT *
FROM (
SELECT REPLACE(BigMacs, ',', '.') AS BigMacs
FROM McTable
WHERE IsNumeric(BigMacs) = 1
) q
WHERE CAST(BigMacs AS DECIMAL) > 6
-----------
123124.123123
There are many ways to accomplish this. Both of these work the same. It is best not to use replace in this situation as there are too many unknowns to account for to replace. It is best to filter everything that is NOT what your after.
SELECT
CONVERT(INT,BigMacs) AS BigMacs
FROM
McTable
WHERE
ISNUMERIC(BigMacs) = 1
AND PATINDEX('%[^0-9]%', BigMacs) = 0
SELECT
CONVERT(INT,BigMacs) AS BigMacs
FROM
McTable
WHERE
ISNUMERIC(BigMacs) = 1
AND BigMacs NOT LIKE ('%[^0-9]%')
Note: It helps if people spell ISNUMERIC() correctly. It also helps if you use the correct syntax order on CONVERT()