Prepend 0s to string (to specific length) [duplicate] - sql

This question already has answers here:
Formatting Numbers by padding with leading zeros in SQL Server
(14 answers)
Closed 9 years ago.
I have a query where I'm pulling in a check number from the database. The return value needs to always be 9 characters exactly. Most of the check numbers are only 6 characters, so I want to prepend 0s to to the string to ensure it is always exactly 9 characters. Since the check numbers can vary in length, it will be a different number of 0s for each one. What's the most efficient way to do this?

If they're always between 6 and 9 digits, the easiest (and probably best) way to go is using CASE.
SELECT CASE WHEN LEN(CHECK_NUM)= 6 THEN '000' WHEN LEN(CHECK_NUM) = 7 THEN '00'
WHEN
LEN(CHECK_NUM) = 8 THEN '0' ELSE '' END + CHECK_NUM
FROM TABLE
EDIT
In case the original values are numbers (int), try something like this:
SELECT CASE WHEN LEN(CHECK_NUM)= 6 THEN '000' WHEN LEN(CHECK_NUM) = 7 THEN '00'
WHEN
LEN(CHECK_NUM) = 8 THEN '0' ELSE '' END + CAST(CHECK_NUM AS VARCHAR(9))
FROM TABLE1
Take a look at the this SQL Fiddle.

Related

How to add a leading 0 in sql-server [duplicate]

This question already has answers here:
Pad a string with leading zeros so it's 3 characters long in SQL Server 2008
(18 answers)
Closed 10 months ago.
I have to add a leading 0 in a column called houses, where it is a unique list of 3 digits, but I wanted have to add a leading 0 to it --> so 4 digits instead of 3.
Can someone help me with this query as the code is incompatible in the '|' operator.
The code is as follows:
select houses from house_numbers
order by houses;
select houses,
case
when len(houses)=3 then '0' | houses
when len(houses)=4 then '' | houses
end as houses
from house_numbers
The string concatenation operator in SQL Server is +, not ||, so you should use:
CASE
WHEN LEN(houses) = 3 THEN '0' + houses
WHEN LEN(houses) = 4 THEN '' + houses
END AS houses
However, a better way to do this would be to just left pad with zero to a length of 4:
RIGHT('0000' + ISNULL(houses, ''), 4) AS houses
You are looking for the CONCAT function here, assuming you are dealing with varchars
when len(houses)=3 then CONCAT('0' , houses)
You could simplify like so
select houses from house_numbers
order by houses;
select houses,
case
when len(houses)=3 then CONCAT('0' , houses)
else houses
end as houses
from house_numbers
Always add the Zero and then strip of the right 4 chars, I believe this might be less resource intensive than doing a case
SELECT RIGHT('0'+CONVERT(VARCHAR(10),345),4) AS Three_Digit_Example,
RIGHT('0'+CONVERT(VARCHAR(10),1345),4) AS Four_Digit_Example

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

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;

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)),

IF statement within a SELECT - SQL [duplicate]

This question already has answers here:
Not equal <> != operator on NULL
(10 answers)
Closed 4 years ago.
I'm trying to write a query, that selects a number of values. I only want it to select one of the values if it isn't null.
I'm trying to use a case when but it is erroring.
SELECT pick_no,
pd.product,
from_warehouse,
to_warehouse,
qty_pick,
qty_check,
qty_picked,
qty_checked,
long_description,
ROUND(qty_pick / stk.pallet_unit_qty, 2) as [PalletQty],
ph.date_picking,
stk.bin_no,
CASE WHEN qty_picked <> null
THEN ROUND(qty_picked / stk.pallet_unit_qty, 2) as [pltCheck]
ELSE '0' END
FROM
Null is a tricky beast, you can't use equality operands on it. Also your else clause was returning a CHAR when the first clause returns a FLOAT :
CASE WHEN qty_picked IS NOT NULL
THEN ROUND(qty_picked / stk.pallet_unit_qty, 2) as [pltCheck]
ELSE 0 END
A simpler way to achieve your goal is to use COALESCE :
COALESCE(ROUND(qty_picked / stk.pallet_unit_qty, 2),0) as [pltCheck]

Sorting varchar column by number, character [duplicate]

This question already has answers here:
How to do sorting on irregular Alphanumeric data in postgres sql
(2 answers)
Closed 10 years ago.
I have a varchar column [flat_number] which has some values as
A1A1A
A1A2A
A1A101A
A3A5A
12
A2
A3
I wish to get the results sorted by number and then by characters first
like
12
A2
A3
A1A1A
A1A2A
A1A101A
A3A5A
I have managed to sort it by number (if the column only contains digits 0-9 using regex, I treat it as a number), then I sort it by character, but it dosent seem to work for column values as A1A101A (having multiple combinations of number and character)
CASE
WHEN length(flat_number) < 10 AND flat_number SIMILAR TO '[0-9]+'
THEN
flat_number::int
END
ELSE
NULL
END,
( SELECT COALESCE( match[1], NULL ) FROM regexp_matches( flat_number, '[^0-9]+' ) AS match ),
( SELECT COALESCE( left( match[1], 9), NULL ) FROM regexp_matches( flat_number, '([0-9]+$)' ) AS match )::int
The current query works as
If the column contains only numbers [0-9] I convert it to int and sort it
ElSE, I split the column into 2 parts and try to extract the column character at the start and the number at the end.
Is there a better wait to do so and also make sure the expected output is returned
I think the following will work:
order by (case when flat_number ~ '^[0-9]+$' then 0 else 1 end),
(case when flat_number ~ '^[0-9]+$' then length(flat_number) end),
flat_number
This orders the number first, uses a trick to put them in numeric order, and then orders the rest of the numbers.