SQL Server - Dynamically Filling the column Values with 0's as per the fixed length - sql

I have a column with the given values
MRN
1946
456
27
557
The column values length is fixed.
If at all any value is less than 6characters,then it should concate 0's to the left and make it 6characters length.
The desired output is
MRN
001946
000456
000027
000557

This is called left paddings. In SQL Server, this is typically done with more basic string operations:
select right(replicate('0', 6) + mrn, 6)
If mrn is a number, then use the concat() function:
select right(concat(replicate('0', 6), mrn), 6)

You can also use the FORMAT function for this. (Demo)
SELECT FORMAT(MRN ,'D6')
FROM YourTable

Change the number 6 to whatever your total length needs to be:
SELECT REPLICATE('0',6-LEN(EmployeeId)) + EmployeeId
If the column is an INT, you can use RTRIM to implicitly convert it to a VARCHAR
SELECT REPLICATE('0',6-LEN(RTRIM(EmployeeId))) + RTRIM(EmployeeId)
And the code to remove these 0s and get back the 'real' number:
SELECT RIGHT(EmployeeId,(LEN(EmployeeId) - PATINDEX('%[^0]%',EmployeeId)) + 1)

We can achieve this by adding leading zero's
select RIGHT('0000'+CAST(MRN AS VARCHAR(10)),6)

Related

Concatenate and add a character to integer columns in SQL

I have a 10 Character length values in a column in SQL Server. I need to split that column at fixed length and remove the leading zeros and add a - after each of the values.
I am able to split the values by using Substring and converting them to int. It is working well.
However, when I try to concatenate it is failing. Appreciate if you can help.
SELECT TOP 1 R.COL1, CAST(SUBSTRING(R.COL1,1,1) AS int) AS F1,CAST(SUBSTRING(R.COL1,2,5) AS int) AS F2,CAST(SUBSTRING(R.COL1,7,4) AS int) AS F3 CAST(SUBSTRING(R.COL1,1,1) AS int) +'-' +CAST(SUBSTRING(R.COL1,2,5) AS int) +'-' + CAST(SUBSTRING(R.COL1,7,4) AS int) AS finalString FROM MYTABLE R
If the value for COL1 IS 1012950001 the finalString I am expecting is 1-1295-1
however the result I am getting from the above query is 1297 as it is adding all the values.
Appreciate if you can help.
You can't use the + operator with a numerical data type and a varchar that cannot implicitly be converted to that data type. Something like 1 + 'a' isn't going to work, as 'a' isn't an int, and can't be implicitly converted to one.
If you are mixing data types, then use CONCAT, which implicitly converts each part into a (n)varchar:
CONCAT({Numerical Expression},'a',{Other varchar Expression})
You can use concat method to concatenate the substring value
select
concat(CAST(SUBSTRING('1012950001',1,1) AS int), '-',
CAST(SUBSTRING('1012950001',2,5) AS int), '-',
CAST(SUBSTRING('1012950001',7,4) AS int)) AS finalString
This will give you the expected result '1-1295-1'

get last _ position values in sql server

Hi I have one doubt in sql server .
how to get first position to right side specific character position.
table : empfiles
filename:
ab_re_uk_u_20101001
ax_by_us_19991001
abc_20181002
I want output like below:
filename
ab_re_uk_u
ax_by_us
abc
I tried like below :
select SUBSTRING(filename,1,CHARINDEX('2',filename) - 1) as filename from empfiles
above query is not given expected result please tell me how to write query to achive this task in sql server .
If last position has always numeric values then you can use patindex():
select *, substring(filename, 1, patindex('%[0-9]%', filename)-2) as NewFile
from empfiles e;
If you want to get characters after than _ to right sight of string then you can use combo to reverse() and substring()
select *,
reverse(substring(reverse(filename),charindex('_', reverse(filename))+1, len(filename)))
from empfiles e;
Another way is to use reverse in combination with STUFF.
create table f(filename nvarchar(100));
insert into f values
('ab_re_uk_u_20101001')
,('ax_by_us_19991001')
,('abc_20181002');
select
filename=reverse(stuff(reverse(filename),1,charindex('_',reverse(filename)),''))
from f
Try This
CREATE TABLE #DATA([FILENAME] NVARCHAR(100));
INSERT INTO #DATA VALUES
('ab_re_uk_u_20101001')
,('ax_by_us_19991001')
,('abc_20181002');
SELECT [filename],
SUBSTRING([filename],0,PATINDEX('%[0-9]%',[filename])-1) AS ExpectedResult
FROM #Data
Result
filename ExpectedResult
--------------------------------------
ab_re_uk_u_20101001 ab_re_uk_u
ax_by_us_19991001 ax_by_us
abc_20181002 abc
Well, obviously the last position value is a date, and the format is YYYYMMDD so its 8 characters, plus, added by underscore character, so that makes its 9 character.
Assumed by the above statement applied, the following logic of the query should work
SELECT SUBSTRING(ColumnText, 1, LEN(ColumnText) - 9)
Which means, only display characters from character position 1, to character position LEN - 9, which LEN is the length of characters, and 9 is the last 9 digit of number to be removed
Try with this ..
select [filename],SUBSTRING([filename],1,PATINDEX('%_[0-9]%',[filename])-1) from empfiles
Individual Select records
SELECT SUBSTRING('ab_re_uk_u_20101001',1,PATINDEX('%_[0-9]%','ab_re_uk_u_20101001')-1)
SELECT SUBSTRING('ax_by_us_19991001',1,PATINDEX('%_[0-9]%','ax_by_us_19991001')-1)
SELECT SUBSTRING('abc_20181002',1,PATINDEX('%_[0-9]%','abc_20181002')-1)

ORA-01722: invalid number - value with two decimals

I'm trying to get the max value from a text field. All but two of the values are numbers with a single decimal. However, two of the values have something like 8.2.10. How can I pull back just the integer value? The values can go higher than 9.n, so I need to convert this field into a number so that I can get the largest value returned. So all I want to get back is the 8 from the 8.2.1.
Select cast(VERSION as int) is bombing out because of those two values with a second . in them.
You may derive by using regexp_substr with \d pattern :
with tab as
(
select regexp_substr('8.2.1', '\d', 1, 1) from dual
union all
select regexp_substr('9.0.1', '\d', 1, 1) from dual
)
select * from tab;
For Oracle you must attend the value as string for retire only the part before the dot. Ex:
SELECT NVL( SUBSTR('8.2.1',0, INSTR('8.2.1','.')-1),'8.2.1') AS SR FROM DUAL;
Check than the value is repeated 3 times in the sentence, and if the value is zero or the value didn't have decimal part then it will return the value as was set.
I had to use T-SQL rather PL/SQL, but the idea is the same:
DECLARE #s VARCHAR(10);
SELECT #s='8.2.1';
SELECT CAST(LEFT(#s, CHARINDEX('.', #s) - 1) AS INT);
returns the integer 8 - note that it won't work if there are no dots because it takes the part of the string to the left of the first dot.
If my quick look at equivalent functions was correct, then in Oracle that would end up as:
SELECT CAST(SUBSTR(VERSION, 1, INSTR(VERSION, '.') - 1) AS INT)

SQL SELECT statement with Cast, LPad and Max

Are there any issues with this select statement ??
SELECT SUBSTR(FIELD_A,10,3) as MOVID,
MAX(LPAD((CAST(SUBSTR(FIELD_A,-3,3) as INT) + 1 ), 3, 0)) as NEXTMOVID
FROM ...
The field is a VARCHAR2.
I want to maintain 3 characters(which are numbers) and add 1 and concatenate with another varchar2
retrieve a portion of the FIELD_A
convert is to an integer
add 1
Left Pad it to 3 characters with 0
Grab the MAX
Later on I concatenate with another field
Wondering if there was a better way to do this ??
As I understand, you need following:
SELECT SUBSTR(FIELD_A,10,3) as MOVID,
to_char(to_number(SUBSTR(FIELD_A, -3, 3)) + 1), '000') as NEXTMOVID
FROM ...

Sum of data in varchar column

i have to sum element in a column(SCENARIO1) that is varchar and contain data like (1,920, 270.00, 0, NULL) but when i try to convert data into int or decimal i get this error :
"he command is wrong when converting value "4582014,00" to int type"
here is my request :
select sum( convert( int, SCENARIO1) )
from Mnt_Scenario_Exercice where code_pere='00000000'
any help please
try this
select sum(cast(replace(SCENARIO1, ',', '.') as decimal(29, 10)))
from Mnt_Scenario_Exercice
where code_pere = '00000000';
If you couldn't convert your '4582014,00' into decimal, there's a chance you have different decimal separator on your server. You could look what it is or just try '.'
4582014,00 should be a decimal
try this (I assume that youre query is working) and changed convert(int into decimal)
select sum(convert(decimal(20,2),replace(SCENARIO1, ',', '.'))) from Mnt_Scenario_Exercice where code_pere='00000000'
The problem is due to the fact that the sum function isn't decoding SCENARIO1 as containing a CSV list of numbers. The way the sum function is usually used is to sum a lot of numbers drawn from multiple rows, where each row provides one number.
Try doing it in two steps. In step 1 convert the table into first normal form perhaps by UNPIVOTING. The 1NF table will have one number per row, and will contain more rows than the initial table.
The second step is to compute the sum. If you want more than one sum in the result, use GROUP BY to create groups, and then select a sum(somecolumn). This will yield one sum for each group.
Try this, I haven't got a way to test yet, but I will test and replace if incorrect.
SELECT sum(CAST (replace(SCENARIO1, ',', '') AS INT))
FROM Mnt_Scenario_Exercice
WHERE code_pere = '00000000';
EDIT: You can use a numeric for the cast if you need 4582014,00 to be 4582014.00
SELECT sum(CAST (replace(SCENARIO1, ',', '.') AS NUMERIC(10,2)))
FROM Mnt_Scenario_Exercice
WHERE code_pere = '00000000';