Always include right most 6 digits, but allow for more digits if they aren't leading zeroes? - sql

This may sound like a weird request, but I have to make an excel sheet with EXACTLY the same format as their old sheet. The values in the column in question will be a numeric code. I need to display up to 8 digits, and no less than 6 digits. The code will only be 7 or 8 digits if the first number in the sequence is not zero. If there are 6 digits or less, I need to display 6 digits including leading zeroes. Here is an example:
The data comes in like this:
000023547612
000000873901
000031765429
000000000941
000000055701
I need those numbers to display as:
23547612
873901
31765429
000941
055701
Is there a way to achieve this in a SQL statement?

You can check the length of the string and use right to pad it. But GSerg's answer is better.
declare #Test table (Number varchar(12))
insert into #Test (Number)
values ('000023547612'),('000000873901'),('000031765429'),('000000000941'),('000000055701')
select Number
, case when len(convert(varchar(12), convert(int, Number))) <= 6 then right('000000'+convert(varchar(12), convert(int, Number)),6) else convert(varchar(12), convert(int, Number)) end
, format(convert(int, Number), N'##000000') -- GSerg's Answer
from #Test
Returns:
Number Attempt1 Attempt2 (GSerg)
000023547612 23547612 23547612
000000873901 873901 873901
000031765429 31765429 31765429
000000000941 000941 000941
000000055701 055701 055701
PS: In future if you provide test data in this format (table variable or temp table) you will make it much easier for people to answer.

You can use
SELECT Substring('0078956', Patindex('%[^0 ]%', '0078956' + ' '), Len('0078956') ) AS Trimmed_Leading_0;

Related

how to repeat characters in a string

I'm trying to link two tables, one has an 'EntityRef' that's made of four alpha characters and a sequential number...
EntityRef
=========
SWIT1
LIVE32
KIRB48
MEHM38
BRAD192
The table that I'm trying to link to stores the reference in a 15 character field where the 4 alphas are at the start and the numbers are at the end but with zeros in between to make up the 15 characters...
EntityRef
=========
SWIT00000000001
LIVE00000000032
So, to get theses to link, my options are to either remove the zeros on one field or add the zeros on the other.
I've gone for the later as it seems to be a simpler approach and eliminates the risk of getting into problems if the numeric element contains a zero.
So, the alpha is always 4 characters at the beginning and the number is the remainder and 15 minus the LEN() of the EntityRef is the number of zeros that I need to insert...
left(entityref,4) as 'Alpha',
right(entityref,len(EntityRef)-4) as 'Numeric',
15-len(EntityRef) as 'No.of Zeros'
Alpha Numeric No.of Zeros
===== ======= ===========
SWIT 1 10
LIVE 32 9
KIRB 48 9
MEHM 38 9
MALL 36 9
So, I need to concatenate the three elements but I don't know how to create the string of zeros to the specified length...how do I do that??
Concat(Alpha, '0'*[No. of Zeros], Numeric)
What is the correct way to repeat a character a specified number of times?
You can use string manipulation. In this case:
LEFT() to get the alpha portion.
REPLICATE() to get the zeros.
STUFF() to get the number.
The query:
select left(val, 4) + replicate('0', 15 - len(val)) + stuff(val, 1, 4, '')
from (values ('SWIT1'), ('ABC12345')) v(val)
You may try left padding with zeroes:
SELECT
LEFT(EntityRef, 4) +
RIGHT('00000000000' + SUBSTRING(ISNULL(EntityRef,''), 5, 30), 11) AS EntityRef
FROM yourTable;
Demo
With casting to integer the numeric part:
select *
from t1 inner join t2
on concat(left(t2.EntityRef, 4), cast(right(t2.EntityRef, 11) as bigint)) = t1.EntityRef
See the demo.
I found the answer as soon as I posted the question (sometimes it helps you think it through!).
(left(entityref,4) + replicate('0',15-len(EntityRef)) +
right(entityref,len(EntityRef)-4)),

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

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)

Query to pad left of a field with 0's [duplicate]

This question already has answers here:
Formatting Numbers by padding with leading zeros in SQL Server
(14 answers)
Closed 7 years ago.
I have been working on a query (in sql Server TSQL) which fills left of a number with 0's so output is always 5 digit.
So:
Select MuNumber From Mytable
for data 11,011,2132,1111
Creates output like
00011
02134
01111
I tried Lpad Function but numer of 0's can be different.
if Munumber is 1 we need 0000 and If MyNumber is 34 we need 000
Assuming that MuNumber is VARCHAR simply use RIGHT
SELECT RIGHT('00000' + MuNumber, 5)
FROM Mytable
Otherwise you need to convert it first
SELECT RIGHT('00000' + CONVERT(VARCHAR(5), MuNumber), 5)
FROM Mytable
And in general you can use this pattern:
DECLARE #num INT = 10;
SELECT RIGHT(REPLICATE('0', #num) + CONVERT(VARCHAR(5), MuNumber), #num)
FROM Mytable
Try this
select right('00000'+cast(col as varchar(5)),5) from table
You can use the user defined function udfLeftSQLPadding where you can find the source codes at SQL Pad Leading Zeros
After you create the function on your database, you can use it as follows
select
dbo.udfLeftSQLPadding(MuNumber,5,'0')
from dbo.Mytable
Another option:
declare #n int = 6
select stuff(replicate('0', #n), 6-len(n), len(n), n)
from (values('123'), ('2493'), ('35')) as x(n)

Pad a number with zeros, but only if it's below a certain length?

I have numbers that must be at least 7 digits long. For example:
0000001
123456789
0012345
Are all valid. I only need to pad the number with 0's only if its length is below 7. How do I do this in SQL Server? The best I've been able to get is to pad the number if the length is less than 7, but above that, it starts to truncate the number instead.
SELECT CASE WHEN LEN(CONVERT(VARCHAR(12), column)) > 7 THEN
CONVERT(VARCHAR(12),column) ELSE
RIGHT('0000000' + CONVERT(VARCHAR(12), column), 7) END
FROM dbo.table;
Aaron Bertrand beat me to it.
I'd like to add that it might also be useful to encapsulate both the character and number of times you have to repeat it, so that if it needs to change sometime in the future, it's easy to do it. You can do this using REPLICATE. So expanding on Aaron's example:
DECLARE #num_digits as int = 7
SELECT RIGHT(REPLICATE('0', #num_digits) + col, #num_digits) FROM dbo.table;
Hi check this out.
declare #num table(num varchar(10))
insert into #num
VALUES('0000001'),('123456789'),('0012345'),('123'),('11')
select CASE when len(num) < 7 then REPLICATE('0',(7-len(num)))+num else num END from #num

sql server decimal formatting in query string

I've found several solutions online, but none that really do what I'm looking for. So, here goes..
I have several columns in my table of type numeric(8, 4), numeric(8, 5), etc, and when I retrieve the data it comes with all the trailing 0's. Is there a way I can format it so it leaves off all the trailing and leading 0's? I don't want to specify a length of precision. Here's some examples of what I'm looking for:
145.5000 -> 145.5
145.6540 -> 145.654
73.4561 -> 73.4561
37.0000 -> 37
Thank you much!
Float and real are both approximate data types so this may not work with every value you come across. Given that you only have 4 or 5 digits of precision, I think this method will always work, but you'll want to test it pretty well before implementing this in to production.
DECLARE #d DECIMAL(8,5)
select #d = 5.12030
Select Convert(Float, #d)
Ideally you want to do this in front-end code
so how will you distinguish between 0.37 and 37.0 if all you want is 37?
Here is one way in SQL
Replace 0 with space and do trim and then replace space back to 0
example
edit: missed the trailing dot before..added that as a case statement
DECLARE #d DECIMAL(8,5)
select #d = 5.12030
SELECT CASE WHEN RIGHT(REPLACE(RTRIM(LTRIM(REPLACE(CONVERT(VARCHAR(100),#d),'0',' '))),' ','0'),1) = '.'
THEN REPLACE(REPLACE(RTRIM(LTRIM(REPLACE(CONVERT(VARCHAR(100),#d),'0',' '))),' ','0'),'.','')
ELSE
REPLACE(RTRIM(LTRIM(REPLACE(CONVERT(VARCHAR(100),#d),'0',' '))),' ','0') END