SQL Server 2005 - Stripping Only Alpha Values from String - sql-server-2005

I am using SQL Server 2005 and I want to extract the alpha part of a string.
i.e.
From ABC123, I would like to get ABC
From AB1234, I would like to get AB.
etc etc.
What is the easiest way to do this?

Always letters then digits i.e. XYZ123 or XZ321 etc – GordyII Mar 2
'10 at 0:26
I know this is an old post BUT... If the quote above is true, then this is easy...
SELECT LEFT(YourStringColumn, PATINDEX('%[0-9]%',YourStringColumn)-1)
FROM dbo.YourTable

You could make a user defined function that would loop through the characters and build up a new string where the characters were letters.

if there is always a space between the letter and the digits, try:
DECLARE #String varchar(100)
SET #String='ABC 123'
SELECT LEFT(#String,LEN(#String)-CHARINDEX(' ',#String))
OUTPUT
-------------------
ABC
(1 row(s) affected)
EDIT after OP's comment, assumes no space before digits:
DECLARE #String varchar(100)
SET #String='ABCD123'
;with Numbers AS
(
SELECT 1 AS Number,ISNUMERIC(SUBSTRING(#String,1,1)) AS Digit
UNION ALL
SELECT Number+1,ISNUMERIC(SUBSTRING(#String,Number+1,1)) AS Digit
FROM Numbers
WHERE Number<LEN(#String)
)
SELECT LEFT(#String,MAX(Number)) FROM Numbers WHERE Digit=0
--OPTION (MAXRECURSION n) --if the string is longer than 100 characters uncomment this and set "n" to the string length
OUTPUT:
-------------------
ABCD
(1 row(s) affected)

You also might consider doing this not in SQL but somewhere else, if it is possible in your scenario. If you explain what kind of data are you working with how they get into your sql database and what and how uses them it might be possible to suggest a better alternative.

Related

Pull 3 digits from middle of id and sort by even odd

I have file ids in my database that start with:
a single character prefix
a period
a three digit client id
a hyphen
a three digit file number.
Example F.129-123
We have several ids for each client.
I need to be able to strip out the three digit file number and then pull them based on even or odd so that I can assign specific data to each result population.
One added issue. Some of the ids have characters added at the end.
Example: F.129-123A or F.129-123.NF
So I need to be able to just use the three digit file number without any other characters, because the added characters create errors while conversion.
If you are using SQL SERVER,
you can use CHARINDEX() to find the index of - and then
get 3 digits after - using SUBSTRING()
SELECT substring('F.123-234',charindex('-','F.123-234')+1, 3)
If you are using MySQL,
you can use POSITION() to find the index of - and then get 3 digits after - using SUBSTRING()
SELECT SUBSTRING('F.123-234',POSITION( '-' IN 'F.123-234' )+1,3);
If you are using Oracle,
you can use INSTR() to find the index of - and then get 3 digits after - using SUBSTR()
UPDATES:
Based on the requirements in comments, you can use a query like below achieve what you need.
SELECT
SUBSTRING(MatterID,CHARINDEX('-',MatterID)+1, 3) as FileNo
FROM
Matters
WHERE
MatterID LIKE'f.129%'
AND MatterID NOT LIKE '%col%'
AND substring( MatterID, CHARINDEX('-',MatterID)+1, 3) % 2 = 0
If you are working with Microsoft SQL Server, then you could use of patindex() function with substring() function to get the only 3 digits file number
select left(substring(string, PATINDEX('%[0-9][-]%', string)+2, LEN(string)), 3)
Note that if you have other period (i.e. -, /) then you will need to modify chars like PATINDEX('%[0-9][/]%')
In Postgres you can use split_part() to get the part after the hyphen, then cast it to an integer:
select *
from the_table
order by split_part(file_id, '-', 2)::int;
This assumes that there is always exactly one - in the string. I understand your question that this is the case as the format is fixed.
Is this helpful
Create table #tmpFileNames(id int, FileName VARCHAR(50))
insert into #tmpFileNames values(1,'F.129-123')
insert into #tmpFileNames values(2,'F.129-125')
insert into #tmpFileNames values(3,'F.129-124')
insert into #tmpFileNames values(4,'F.129-123A')
insert into #tmpFileNames values(5,'F.129-124B')
insert into #tmpFileNames values(6,'F.129-125.PQ')
insert into #tmpFileNames values(7,'F.129-123.NF')
select SUBSTRING(STUFF(FileName, 1, CHARINDEX('-',FileName), ''),0,4), * from #tmpFileNames
Order by SUBSTRING(STUFF(FileName, 1, CHARINDEX('-',FileName), ''),0,4),id
Drop table #tmpFileNames

SQL : REGEX MATCH - Character followed by numbers inside quotes

I have a column in sql which holds value inside double quotes like "P1234567" , "P1234" etc..
I need to identify only columns which start with letter P and is followed by seven digits (numbers) only. I tried where column like'"P[0-9][0-9][0-9][0-9][0-9][0-9][0-9]"' but it doesn't seem to work.
Can someone please correct me or point me to a thread which can help me out?
Thanks
Standard SQL has no regex support, but most SQL engines have regex extensions added to them on top of the standard SQL. So, for example, if you're using MySQL then you'd do this:
... WHERE column REGEXP '^"P[0-9]{7}"'
And if you're using Postgres then that would be:
... WHERE column ~ '^"P[0-9]{7}"'
(updated to match the double-quote part of the question, I'd misunderstood that to begin with)
How about using length and isnumeric:
Select
*
from
mytable
where
mycolumn like '"P%'
and len(mycolumn) = 10 --2 chars for quotes + 1 for 'P' + 7 for the digits
and isnumeric(substring(mycolumn, 3, 7))=1
This answer is for SQL Server, other DBMS's may have a different syntax for length

SQL: Finding dynamic length characters in a data string

I am not sure how to do this, but I have a string of data. I need to isolate a number out of the string that can vary in length. The original string also varies in length. Let me give you an example. Here is a set of the original data string:
:000000000:370765:P:000001359:::3SA70000SUPPL:3SA70000SUPPL:
:000000000:715186816:P:000001996:::H1009671:H1009671:
For these two examples, I need 3SA70000SUPPL from the first and H1009671 from the second. How would I do this using SQL? I have heard that case statements might work, but I don't see how. Please help.
This works in Oracle 11g:
with tbl as (
select ':000000000:370765:P:000001359:::3SA70000SUPPL:3SA70000SUPPL:' str from dual
union
select ':000000000:715186816:P:000001996:::H1009671:H1009671:' str from dual
)
select REGEXP_SUBSTR(str, '([^:]*)(:|$)', 1, 8, NULL, 1) data
from tbl;
Which can be described as "look at the 8th occurrence of zero or more non-colon characters that are followed by a colon or the end of the line, and return the 1st subgroup (which is the data less the colon or end of the line).
From this post: REGEX to select nth value from a list, allowing for nulls
Sorry, just saw you are using DB2. I don't know if there is an equivalent regular expression function, but maybe it will still help.
For the fun of it: SQL Fiddle
first substring gets the string at ::: and second substring retrieves the string starting from ::: to :
declare #x varchar(1024)=':000000000:715186816:P:000001996:::H1009671:H1009671:'
declare #temp varchar(1024)= SUBSTRING(#x,patindex('%:::%', #x)+3, len(#x))
SELECT SUBSTRING( #temp, 0,CHARINDEX(':', #temp, 0))

T/SQL - String Manipulation

I have the below query.
SQLFiddle
I can only have possible 7 characters (- and A-Z combined)
There can only be ONE "-" for first 5 characters (Monday to Friday)
For Saturday and Sunday, we can only have one character or dash
I am replacing Sa and Su with just S
However, whenever they are passing in TWO dashes for Saturday AND/OR Sunday, I need to replace them with ONE dash for each
so length can only be 7 after all manipulations.
I have tried w/e I could but getting stuck at the two vs one dash scenario for Saturday/Sunday position.
Please help! I will keep this updated as I find more.
THX in ADV
Code:
CREATE Table TempTable (string varchar(50))
INSERT INTO TempTable (string)
VALUES ('MTWRFSS')
,('MTWRFSaS')
,('MTWRFSaSu')
,('----F--')
,('----F----')
,('MT------')
,('MT------')
,('----FSa--')
,('----FSa-')
,('----FS--')
,('----FS-')
,('----F-Su')
,('----F--Su')
,('----F-S')
,('----F--S')
UPDATE TempTable
SET string = REPLACE(REPLACE(RTRIM(LTRIM(string)),'SA','S'),'SU','S')
SELECT string
,LEN(String) AS stringLengh FROM TempTable
--DROP TABLE TempTable
Try to manipulate only characters after 5th, because from MON to FRY you always have 1 -.
So I think this will work:
SELECT
string as InitialString
,LEFT(LEFT(String,5) + replace(replace(replace(RIGHT(String,LEN(String)-5),
'Sa','S'),'Su','S'),'--','-') + '--',7) as FinalString
FROM TempTable;
You have to cut string into 2: left 5 and the rest. Then using several replaces you can have correct Sat/Sun combination. Concatenate both and you will have final decision.
Also 2 more dashes have to be added and the you have to take only LEFT 7, because if you have '--' it will be replaced with '-'.

How to get rightmost 10 places of a string in oracle

I am trying to fetch an id from an oracle table. It's something like TN0001234567890345. What I want is to sort the values according to the right most 10 positions (e.g. 4567890345). I am using Oracle 11g. Is there any function to cut the rightmost 10 places in Oracle SQL?
You can use SUBSTR function as:
select substr('TN0001234567890345',-10) from dual;
Output:
4567890345
codaddict's solution works if your string is known to be at least as long as the length it is to be trimmed to. However, if you could have shorter strings (e.g. trimming to last 10 characters and one of the strings to trim is 'abc') this returns null which is likely not what you want.
Thus, here's the slightly modified version that will take rightmost 10 characters regardless of length as long as they are present:
select substr(colName, -least(length(colName), 10)) from tableName;
Another way of doing it though more tedious. Use the REVERSE and SUBSTR functions as indicated below:
SELECT REVERSE(SUBSTR(REVERSE('TN0001234567890345'), 1, 10)) FROM DUAL;
The first REVERSE function will return the string 5430987654321000NT.
The SUBSTR function will read our new string 5430987654321000NT from the first character to the tenth character which will return 5430987654.
The last REVERSE function will return our original string minus the first 8 characters i.e. 4567890345
SQL> SELECT SUBSTR('00000000123456789', -10) FROM DUAL;
Result: 0123456789
Yeah this is an old post, but it popped up in the list due to someone editing it for some reason and I was appalled that a regular expression solution was not included! So here's a solution using regex_substr in the order by clause just for an exercise in futility. The regex looks at the last 10 characters in the string:
with tbl(str) as (
select 'TN0001239567890345' from dual union
select 'TN0001234567890345' from dual
)
select str
from tbl
order by to_number(regexp_substr(str, '.{10}$'));
An assumption is made that the ID part of the string is at least 10 digits.