How to truncate a numeric-string data member in a SQL query - sql

In my sql database I have a table like "REG_DET", This table mainly include 3 data member. NAME,AGE,SSN. Here SSN is a string include more than 10 character. Here my problem is when i read SSN from the table i need only last 4 character that is
Eg. Rohith , 25 , 1023456457
result only include Rohith , 25 ,6457(last 4 character of SSN)
Is It possible to do it in a sql select query(at the time of selection). If anyone know pls help me

You can use RIGHT function:
SELECT NAME,
AGE,
RIGHT(SSN, 4) As SSN_Short
FROM REG_DET
(assuming that you're using SQL-Server or MySQL)
Edit: Since you're using TEXT, you need to conver it to VARCHAR first:
SELECT NAME,
AGE,
RIGHT(CONVERT(VARCHAR(8000),SSN)), 4) As SSN_Short
FROM REG_DET

Yes it is possible with the RIGHT function:
SELECT NAME, AGE, RIGHT(SSN, 4) FROM REG_DET

To get the last 4 digits from the SSN column , you can also use SUBSTRING. If the length of the SSN column is 10, then you can use the following query:
SELECT NAME, AGE, SUBSTRING(SSN, 6, 4) FROM REG_DET

Related

How to extract the specific part of string in SQL server?

I have a string ST0023_Lamb_Weston_2017_US in a table from particular column. While selecting the name I need to get only Lamb_Weston_2017_US. I can use
SELECT SUBSTRING('ST0023_Lamb_Weston_2017_US', 8, 20)
But there will be different names in the column. For example ,
ST0023_Lamb_Weston_2017_US
ST0053_PL_Sandbox_Dorgan_US
ST0071_EDA_Austria
ST0071_EDA_Austria
ST10338_Nestle_Soluble_Instant_Cacao_ES
So the above mentioned are the different names available. I need to remove the "ST" part and the number part till first hyphen and return name alone. Please help me with this.
Inside substring function use charindex to pick the starting position of underscore. Plus one is added with charindex to exclude the underscore position and ending position will be considered till the length of the data.
create table data
(
value varchar(100)
)
insert into data
select 'ST0023_Lamb_Weston_2017_US' union
select 'ST0053_PL_Sandbox_Dorgan_US' union
select 'ST0071_EDA_Austria' union
select 'ST0071_EDA_Austria' union
select 'ST10338_Nestle_Soluble_Instant_Cacao_ES'
go
select value, SUBSTRING(value, CHARINDEX('_',value)+1 , LEN(value)) 'Newvalue' from data

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)

Instr - Last index of last character

I'm using an Oracle 11g DB and I want to find the position of the last character of a string.
For example:
"City=Amsterdam"
The string in this case would be "City=", I would like to get the position of the "=".
I know INSTR(Input,'City=', 1, 1)+4, would kinda work but I am looking for another way.
edit: Basically I want to use a substr function to extract "Amsterdam". But the select statement should be as clean as possible.
What I forgot to mention, the string contains more than "City=Amsterdam", it contains also "Customer=124"
"City=Amsterdam"; "Customer=124"
INSTR('City=Amsterdam', '=', -1)
use -1 for start pos!
from your comment, answer 2
select SUBSTR( input, INSTR(input, '=', -1)+1 ) as city
from yourTable;
And if you have more fields, before or after, as you mentions with customer=... you can do:
select substr(input,
INSTR(input,'City=')+5,
INSTR(input,'"', INSTR(input,'City='))-INSTR(input,'City=')-5
) as city from city;
And some kind of "fancy" query, to comment and make it more flexible with other fields...
select substr(c.input, c.citystart, c.cityend - c.citystart) as city
from (
select input as input,
INSTR(input,'City=')+5 as citystart,
INSTR(input,'"', INSTR(input,'City=')) as cityend
from city) c;
Test data:
create table city (input char(64));
insert into city values('"City=Amsterdam"; "Customer=124"');
insert into city values('"Customer=11"; "City=USA"');
insert into city values('"Tel=+00"; "City=China"; "Customer=1"');
insert into city values('"Tel=+00"; "Post=11111"; "Customer=333"; "City=Canada"');
See updated SQLFIDDLE:
Wouldn't you actually use:
INSTR(Input,'City=')+ length('City=') - 1
This seems to be the optimal code.

Extract required data with details from SQL data table

I have below data in SQL Database
Path
------------
Mb\Dbi\Abc
Mb\Dbi\Abc\123
Mb\Dbi\Dks
Mb\Dbi\Abc\Hig
Mb\Dbi\Abc\123\Xyz
Mb\Dbi\Abc
Mb\Dbi\Abc\Hig
Mb\Dbi\Abc\123
Mb\Dbi\Hig
Mb\Dbi\Dks\67H
I want to extract the above data in below format, Here "Mb\Dbi" remains constant and need to extract distinct Names after that and also need their exact value path.
Sr. Name Value
1 Abc Mb\Dbi\Abc
2 Abc\123 Mb\Dbi\Abc\123
3 Dks Mb\Dbi\Dks
4 Abc\Hig Mb\Dbi\Abc\Hig
5 Abc\123\Xyz Mb\DbiAbc\123\Xyz
6 Dks\67H Mb\Dbi\Dks\67H
What will be the query/stored procedure /function to accomplish this?
Thanks
You haven't specified what database server you are using.
Either way, you need to search for a replace function.
In SQL Server, the function is replace, you can find the definition here: http://msdn.microsoft.com/es-es/library/ms186862(v=sql.105).aspx
Your query will look like this in SQL Server:
Select replace(subquery.path,'Mb\Dbi','') AS Name, subquery.path as Value from (Select distinct path from {yourtable}) subquery
Regards
If You also want to generate the Serial Number:
SELECT (ROW_NUMBER() OVER ( ORDER BY [Path])) AS [Sr.]
,REPLACE ([Path],'Mb\Dbi','') AS [Name]}
,[Path] AS [Value]}
FROM tbl_PathValues
Or you can have the target table with a column predefined as an Identity column.
Try something like:
SELECT RIGHT(Value, (SELECT LENGTH(Value) - 6))
Try somthing like this,
SELECT RIGHT(DB.Path,SELECT LENGTH(DB.Path) - 6) AS 'Name', DB.Path AS 'Value' FROM DB;
You need to insert your data into Database by escaping '\'. Further following query will solve your problem:
Solution is for MySQL
SELECT #rownum := #rownum + 1 AS 'Sr.',SUBSTRING(path, 8) AS `name`, path AS VALUE FROM test_path, (SELECT #rownum := 0) r;
Hope it helps...

SQL Using ORDER BY with UNION doesn't sort numbers correctly (e.g. 10 before 8)

I've tried looking for the answer, and read many threads on this site, but still can't find the answer I'm looking for.
I am trying to sort a series of numbers that are real look-ups and also one * which isn't, I can sort fine when I don't need to add the fake * but not after.
I have tried
SELECT DISTINCT MasterTable.ClassName, MasterTable.ClassYear
FROM MasterTable
UNION ALL
SELECT DISTINCT "*" As [ClassName], "1" As [ClassYear]
FROM MasterTable
ORDER BY MasterTable.ClassYear;
And
SELECT DISTINCT MasterTable.ClassName, MasterTable.ClassYear
FROM (
SELECT DISTINCT MasterTable.ClassName, MasterTable.ClassYear FROM MasterTable
UNION
SELECT DISTINCT "*" As [ClassName], "1" As [ClassYear] FROM MasterTable
)
ORDER BY MasterTable.ClassYear;
But both return the ClassYear as 1, 10, 12, 8... rather than 1, 8, 10, 12....
Any help would be much appreciated,
Thanks :)
MasterTable.ClassYear is varchar so it will sort as a string.
You'll have to convert it in the query or fix the column type.
For the 2nd clause, you also need only:
SELECT "*" As [ClassName], "1" As [ClassYear] --No FROM MasterTable
However, you can "cheat" and do this. Here 1 will be int and will force a conversion to int from the 1st clause because
SELECT "*" As [ClassName], 1 As [ClassYear] --force int. And fixed on edit
UNION ALL
SELECT DISTINCT MasterTable.ClassName, MasterTable.ClassYear
FROM MasterTable
ORDER BY ClassYear; --no table ref needed
It's property sorting those values as strings. If you want them in numerical order, try something like Cast(MasterTable.ClassYear AS int), either in the select or in the order by, or both, depending on how you end up structuring your query.
And instead of SELECT ..., "1" As [ClassYear], write SELECT ..., 1 As [ClassYear].
You are returning the year as a string, not a number. That means that it's sorted as text, not numerically.
Either return the year as a number, or convert the value into a number when sorting it.