Need to pad zeros left and right for a string value according to decimal format - sql

So if I have a data (varchar) like say 10.1
I need the value as 0000101000000.
means (000010) whole number and (1000000) decimal value.
Its a 13 character string ,numbers coming before decimal point should be in first 6 characters and numbers coming after decimal point should be in last 7 characters

Maybe..?
DECLARE #d decimal(13,7) = 10.1;
SELECT RIGHT('0000000000000' + CONVERT(varchar(13),CONVERT(bigint,(#d * 10000000))),13);
Using my crystal ball here though.
Edit: As, for some reason, the OP is storing a decimal as a varchar (this is a really bad bad idea on it's own), I have added further logic to attempt to convert the value to a decimal first.
As experience has taught many of us, give a user a non-numeric column to store a numeric value in and they're more than happily store a non-numeric value in it, so i have used TRY_CONVERT and assumed you are using SQL Server 2012+:
DECLARE #d varchar(13) = 10.1;
SELECT RIGHT('0000000000000' + CONVERT(varchar(13),CONVERT(bigint,(TRY_CONVERT(decimal(13,7),#d) * 10000000))),13);

SELECT REPLICATE('0',6-LEN(SUBSTRING(CAST([data] AS VARCHAR), 1,
CHARINDEX('.',CAST([data] AS VARCHAR)) -1)))+SUBSTRING(CAST([data] AS VARCHAR), 1,
CHARINDEX('.',CAST([data] AS VARCHAR)) -1)+
SUBSTRING(CAST([data] AS VARCHAR), CHARINDEX('.',CAST([data] AS VARCHAR)) + 1,
LEN(CAST([data] AS VARCHAR)))+REPLICATE('0',7-LEN(SUBSTRING(CAST([data] AS VARCHAR), CHARINDEX('.',CAST([data] AS VARCHAR)) + 1,
LEN(CAST([data] AS VARCHAR))))) AS Whole
FROM Table1
Output
Whole
0000101000000
Demo
http://sqlfiddle.com/#!18/8649d/16

You can use some math and string operations to do it like below
see live demo
declare #var decimal(10,4)
set #var=10.1
select #var,
right(cast(cast(( floor(#var)+ power(10,7)) as int) as varchar(13)),6)
+
cast(cast(((#var- floor(#var)) * power(10,7)) as int) as varchar(13))

There's a fair amount of string manipulation to be done here. I'll step through what I did.
I used a variable for the base number so I could verify different results:
declare #n decimal(9,3) = 10.1
You need 6 spaces left of the decimal and 7 spaces to the right, so I'm doing all the manipulation on a VARCHAR(13). I didn't create a new variable as a VARCHAR because I'm assuming you want to be able to do this conversion in line on the fly, so I'm using that CAST over and over again.
Start by finding the decimal place.
SELECT CHARINDEX('.',CAST(#n as VARCHAR(13)))
In the sample number, that's a 3, but it could obviously change.
Now, get the portion of the number to the left of the decimal place.
SELECT SUBSTRING(CAST(#n as VARCHAR(13)),1,CHARINDEX('.',CAST(#n as VARCHAR(13)))-1)
Then get the portion to the right of the decimal.
SELECT SUBSTRING(CAST(#n as VARCHAR(13)),CHARINDEX('.',CAST(#n as VARCHAR(13)))+1,LEN(CAST(#n as VARCHAR(13))))
Pad the leading zeroes. Put 6 on, concatenate, and take a RIGHT 6. Accounts for no digits to the left of the decimal.
SELECT RIGHT(REPLICATE(0,6) + SUBSTRING(CAST(#n as VARCHAR(13)),1,CHARINDEX('.',CAST(#n as VARCHAR(13)))-1), 6)
Pad the trailing zeroes. Same idea, but in the other direction.
SELECT LEFT(SUBSTRING(CAST(#n as VARCHAR(13)),CHARINDEX('.',CAST(#n as VARCHAR(13)))+1,LEN(CAST(#n as VARCHAR(13)))) + REPLICATE(0,7),7)
Then put it all together.
SELECT RIGHT(REPLICATE(0,6) + SUBSTRING(CAST(#n as VARCHAR(13)),1,CHARINDEX('.',CAST(#n as VARCHAR(13)))-1), 6)
+
LEFT(SUBSTRING(CAST(#n as VARCHAR(13)),CHARINDEX('.',CAST(#n as VARCHAR(13)))+1,LEN(CAST(#n as VARCHAR(13)))) + REPLICATE(0,7),7)
Results.
0000101000000

declare #var varchar(20) = '10000.112'
SELECT FORMAT (FLOOR(#var), '000000') + left((PARSENAME(#var,1)) + replicate('0',7),7)

Related

Need help in converting some values in my SQL Table Column to decimal

I have a Varchar column which have data such as 1.025407162E7, 1.268479084E7 basically it contains something called as E7. How can i convert it to decimal ?
I have tried to convert it to decimal, I could have removed the E7 and moved the decimal point 7 steps forward or Add 7 zeros if there are no so many numbers. But I was looking for a right approach to do it.
CONVERT(DECIMAL(27, 7), ETL_AM.BNK_SHR_LGR_BAL_AMT)
So the actual values look different
1.025407162E7 = 10254071.6200000 and 1.268479084E7 = 12684790.8400000
That's a valid float constant for SQL Server. So convert the string to a float, and then to a decimal.
CONVERT(DECIMAL(27, 7), cast(ETL_AM.BNK_SHR_LGR_BAL_AMT as float))
eg
select convert(decimal(27,7), cast( '1.025407162E7' as float) )
returns
10254071.6200000
Okay, So Error_2646 has taken me in right direction. I converted the value to REAL then converted to decimal.
CASE WHEN SF_FAM.FinServ__Balance__c like '%E%' THEN CONVERT(DECIMAL(27, 7), CONVERT(float(27), SF_FAM.FinServ__Balance__c))
ELSE CONVERT(DECIMAL(27, 7), SF_FAM.FinServ__Balance__c) END
If it is an exponential function, a simple select, after converting it to a float can give you the decimal.
SELECT CAST('1.025407162E7' AS FLOAT)
Otherwise, if E is a random character and if you want to do the calculatoin, you can do it using a case statement.
DECLARE #value VARCHAR(100)
SET #value = '1.025407162E7'
SELECT CASE WHEN #value like '%E7%'
THEN (1.025407162 * 10000000)
END

Splitting field and adding decimal point to create numeric value SQL

I have a field in SQL Server 2014 that I am working with that looks like this:
**RawField**
20060202
20060323
I want to add a split the field and add a decimal point and create a numerical field. This is what I would like to see:
**RawField**
200602.02
200603.23
So I need to split the field, add the decimal point, and convert to a numerical value. I tried some code but was getting an error. Please see my code below:
select top 1000 cast(SUBSTRING(cast(RawField as varchar(6)),1,6) + cast('.' as varchar(1)) + SUBSTRING(cast(RawField as varchar(2)),6,2) as int)
from Table
I get an error of:
Msg 245, Level 16, State 1, Line 11
Conversion failed when converting the varchar value '200602.' to data type int.
Is this a good approach?
you want to convert the string to numeric with 2 decimal places ?
select convert(decimal(10,2), RawField) / 100.0
I guest your RawField contains other alphanumeric after that and you only posted the first 8 characters ?
this should work. Just take the first 8 characters and convert. Simple and direct
select convert(decimal(10,2), left(RawField, 8)) / 100.0
Please try this.
select top 1000 cast(SUBSTRING(cast(RawField as varchar(6)),1,6) + cast('.' as varchar(1)) + SUBSTRING(cast(RawField as varchar(2)),6,2) as numeric(8,2))
from Table
You are trying to cast string with decimal number to int.
Use float/numeric/decimal when casting
select cast(SUBSTRING(RawField ,1,6) + cast('.' as varchar(1)) + SUBSTRING(RawField ,7,2) as numeric(16,2))

How can I find part of a string between two words?

I want to get a part of text from my field description
Could someone offer some advice?
The whole string is 'Version100][BuildNumber:666][SubBuild:000]' and the build number is what I want to single out (however the number may change).
I have tried SUBSTRING with CHARINDEX but I can't seem to figure it out.
I've been googling for about 30 minutes and I can't seem to work it out.
little long, but you could do this.
DECLARE #Description VARCHAR(MAX)= '[Version100][BuildNumber:666][SubBuild:000]'
SELECT LEFT(STUFF(#Description, 1, PATINDEX('%BuildNumber%', #Description) + 11, '' )
,PATINDEX('%]%', STUFF(#Description, 1, PATINDEX('%BuildNumber%', #Description) + 11, '' )) - 1)
You can try this:
SELECT SUBSTRING([description],CHARINDEX('BuildNumber:',[description])+12,
CHARINDEX(']',[description], CHARINDEX('BuildNumber:',[description]))
-(CHARINDEX('BuildNumber:',[description])+12))
FROM YOURTABLE
I haven't actually tested this (numeric offsets might be a bit off, but you can tweak them), but assuming the string formats are always the same, then the following should work, irrespective of the number of digits in the build number.
SELECT SUBSTRING(description,
CHARINDEX('BuildNumber', description) + 11, --The position after BuildNumber: (a)
CHARINDEX('][SubBuild', description) - 3 - CHARINDEX('BuildNumber', description) + 11)) --The distance from (a) to the square brackets before SubBuild
Hope this query can return your expected result with out hard-coding the build number count:
DECLARE #Description AS VARCHAR (500) = 'Version100][BuildNumber:6663211][SubBuild:000]';
DECLARE #BeforeString AS VARCHAR (100) = '[BuildNumber:';
DECLARE #BeforeStringPosition AS INT = CHARINDEX(#BeforeString, #Description);
SELECT SUBSTRING(#Description, #BeforeStringPosition + LEN(#BeforeString) , CHARINDEX('][SubBuild', #Description) - #BeforeStringPosition - LEN(#BeforeString));

Adding leading zeros to result from substring in SQL Server 2008

I have a substring which pulls the data I need but I need to add a leading zero to the front of the result. I've searched and found several samples of pulling data with leading zeros but none using a substring. I can add the zero to the end of the result but do not know how to add it to the front. The substring I am using is shown below.
"substring((substring(convert(char(6),Convert(int,a.nor_ppd_hrs_no*100) + 100000),3,4) + space(16)),1,16) as 'ApprovedHrs',"
This produces a result like this 7500 and I need it to look like this 07500.
Thanks
One of most simple solution for adding leading zeros in order to get a number with a desired width (ex. 16 digits) is to concatenate a string of zeros (REPLICATE('0', 15) or '000000000000000') with the source number (ex. 123) converted to VARCHAR ('123'). Then, the result '000000000000000123' is truncated to desired length (ex. 16 digits) using the RIGHT function:
DECLARE #Num INT;
SET #Num = 123;
SELECT RIGHT(REPLICATE('0', 15) + CONVERT(VARCHAR(11), #Num), 16) AS NumWithLeadingZeros1
SELECT RIGHT('000000000000000' + CONVERT(VARCHAR(11), #Num), 16) AS NumWithLeadingZeros2
Output:
NumWithLeadingZeros1
--------------------
0000000000000123
NumWithLeadingZeros2
--------------------
0000000000000123
Assuming you need the resulting string to be 5 characters length,
stuff(substring((substring(convert(char(6),Convert(int,a.nor_ppd_hrs_no*100) + 100000),3,4) + space(16)),1,16), 1, 0, replicate('0', 5 - len(substring((substring(convert(char(6),Convert(int,a.nor_ppd_hrs_no*100) + 100000),3,4) + space(16)),1,16)))) as 'ApprovedHrs
Use the STR() function to convert a number to a fixed-length, right-justified string. By default, it pads with spaces, so replace ' ' with '0' to get a zero-padded output.
SELECT REPLACE(STR(a.nor_ppd_hrs_no*100,5),' ','0') FROM MyTable

cast or convert a float to nvarchar?

I need to select from one column of datatype float and insert it in another column as nvarchar.
I tried to cast it: cast([Column_Name] as nvarchar(50))
The result was 9.07235e+009 instead of a 10 digit number (phone number).
Does any one know how to cast or convert this data properly?
Check STR. You need something like SELECT STR([Column_Name],10,0) ** This is SQL Server solution, for other servers check their docs.
If you're storing phone numbers in a float typed column (which is a bad idea) then they are presumably all integers and could be cast to int before casting to nvarchar.
So instead of:
select cast(cast(1234567890 as float) as nvarchar(50))
1.23457e+009
You would use:
select cast(cast(cast(1234567890 as float) as int) as nvarchar(50))
1234567890
In these examples the innermost cast(1234567890 as float) is used in place of selecting a value from the appropriate column.
I really recommend that you not store phone numbers in floats though!
What if the phone number starts with a zero?
select cast(0100884555 as float)
100884555
Whoops! We just stored an incorrect phone number...
Do not use floats to store fixed-point, accuracy-required data.
This example shows how to convert a float to NVARCHAR(50) properly, while also showing why it is a bad idea to use floats for precision data.
create table #f ([Column_Name] float)
insert #f select 9072351234
insert #f select 907235123400000000000
select
cast([Column_Name] as nvarchar(50)),
--cast([Column_Name] as int), Arithmetic overflow
--cast([Column_Name] as bigint), Arithmetic overflow
CAST(LTRIM(STR([Column_Name],50)) AS NVARCHAR(50))
from #f
Output
9.07235e+009 9072351234
9.07235e+020 907235123400000010000
You may notice that the 2nd output ends with '10000' even though the data we tried to store in the table ends with '00000'. It is because float datatype has a fixed number of significant figures supported, which doesn't extend that far.
For anyone willing to try a different method, they can use this:
select FORMAT([Column_Name], '') from YourTable
This will easily change any float value to nvarchar.
Float won't convert into NVARCHAR directly, first we need to convert float into money datatype and then convert into NVARCHAR, see the examples below.
Example1
SELECT CAST(CAST(1234567890.1234 AS FLOAT) AS NVARCHAR(100))
output
1.23457e+009
Example2
SELECT CAST(CAST(CAST(1234567890.1234 AS FLOAT) AS MONEY) AS NVARCHAR(100))
output
1234567890.12
In Example2 value is converted into float to NVARCHAR
You can also do something:
SELECT CAST(CAST(34512367.392 AS decimal(30,9)) AS NVARCHAR(100))
Output:
34512367.392000000
I had same problem and i saw your solution.
Good solution, its worked, thank you...
I created a function with your codes. Now i use it.
My function is here:
create function dbo.fnc_BigNumbertoNvarchar (#MyFloat float)
returns NVARCHAR(50)
AS
BEGIN
RETURN REPLACE (RTRIM (REPLACE (REPLACE (RTRIM ((REPLACE (CAST (CAST (#MyFloat AS DECIMAL (38 ,18 )) AS VARCHAR( max)), '0' , ' '))), ' ' , '0'), '.', ' ')), ' ','.')
END
Continuing a1ex07's answer - to use STR function (SQL SERVER),
and Ronen Festinger's comment - that he gets asterisks instead of digits,
I wanted to point out that the default length of STR is 10,
therefore, for large numbers, don't forget to use the length argument
For example: STR(1234567890123, 14)
DECLARE #MyFloat [float]
SET #MyFloat = 1000109360.050
SELECT REPLACE (RTRIM (REPLACE (REPLACE (RTRIM ((REPLACE (CAST (CAST (#MyFloat AS DECIMAL (38 ,18 )) AS VARCHAR( max)), '0' , ' '))), ' ' , '0'), '.', ' ')), ' ','.')