Split string to array and order arr[1] ? - MS SQL - sql

I want to order a value like 1234_1 (id, index) in correct way. Remove 123_ and then just order the index. How can i do it in right way in Microsoft SQL... Cheers

Try using Substring and charindex :
To order by it :
SELECT ...
FROM ...
ORDER BY SUBSTRING(YourColumn, CHARINDEX('_', YourColumn) + 1, LEN(YourColumn))

Presumably, you want to order by the index numerically (so _10 is after _9 rather than _1).
You can extract the value and convert to a number:
order by try_convert(int, stuff(col, 1, charindex('_', col), ''))

Related

How can I use SQL Substring to extract characters from this filename?

I'm attempting to use the SUBSTRING function to extract a name out of a filename.
An example filename would be: "73186_RHIMagnesita_PHI_StopLoss_TruncSSN_NonRedact_Inc_to_Apr2022_Paid_to_Apr2022_EDIT"
I'm attempting to extract the "RHIMagnesita" from this filename.
The substring I used was:
SUBSTRING(DFH.FileName, CHARINDEX('_', DFH.FileName) + 1, CHARINDEX('_PHI', DFH.FileName) - 1)
The results it gave were: "RHIMagnesita_PHI_S"
How do I extract only "RHIMagnesita" using the Substring function?
The third parameter in SUBSTRING is length not position, so you would need to substract the length of the beginning string.
SUBSTRING(DFH.FileName, CHARINDEX('_', DFH.FileName) + 1, CHARINDEX('_PHI', DFH.FileName) - CHARINDEX('_', DFH.FileName))
You might need to add or substract 1, but that's the idea.
You were close. You need to use CHARINDEX to also find the position of the second underscore.
SELECT SUBSTRING(FileName,
CHARINDEX('_', FileName) + 1,
CHARINDEX('_', FileName, CHARINDEX('_', FileName) + 1) -
CHARINDEX('_', FileName) - 1) AS FilePart
FROM yourTable;
Here's a way using STRING_SPLIT and FETCH, rather than SUBSTRING We split the string and only return the second row
SELECT
value
FROM STRING_SPLIT('73186_RHIMagnesita_PHI_StopLoss_TruncSSN_NonRedact_Inc_to_Apr2022_Paid_to_Apr2022_EDIT','_')
ORDER BY (SELECT NULL)
OFFSET 1 ROWS
FETCH NEXT 1 ROWS ONLY;
Note: On Azure Sql Server STRING_SPLIT has an ordinal parameter, so you could write this
SELECT
value
FROM
STRING_SPLIT('73186_RHIMagnesita_PHI_StopLoss_TruncSSN_NonRedact_Inc_to_Apr2022_Paid_to_Apr2022_EDIT','_', 1)
WHERE ordinal = 2

Get text after second occurrence of a specific character

I have a column with data like this:
firstNameLetter_surname_numericCode
For example:
m_johnson_1234
I need to extract the numeric code. I've tried with SUBSTRING function but I just get:
surname_numericCode
This is the code I've used:
SET number = substring(t2.code, charindex('_', t2.code, 2) + 1, len(t2.code))
How can I get just the numeric code?
Heres a one-liner for you
select right('m_johnson_1234', charindex('_', reverse('m_johnson_1234') + '_') - 1)
Call the CHARINDEX function twice:
SELECT SUBSTRING(
code,
NULLIF(CHARINDEX('_', code, NULLIF(CHARINDEX('_', code), 0) + 1), 0) + 1,
LEN(code)
)
FROM (VALUES
('a_b_c'),
('a_b')
) x(code)
One method is to look for the first _ in the reversed string:
select col,
stuff(col, 1, len(col) - charindex('_', reverse(col)) + 1, '') as numericCode
from (values ('firstNameLetter_surname_numericCode')) v(col);
If the numeric code is really a number -- and no other numbers start the preceding values -- then you can use patindex():
select col,
stuff(col, 1, patindex('%[_][0-9]%', col), '') as numericCode
from (values ('firstNameLetter_surname_0000')) v(col);
The SUBSTR and INSTR functions can be combined to get you the numeric code.
SELECT SUBSTR('m_johnson_1234', INSTR('m_johnson_1234', '_', 1, 2)+1) FROM TABLE;
For the start_pos argument use INSTR to start at the beginning of the string, and find the index of the second instance of the '_' character. Then use that to start one position after and read to the end of the string.
If you need the result to be numeric instead of still a string, then wrap the SUBSTR() in a TO_NUMBER() function.
Late answer, and just because I didn't see PARSENAME() mentioned.
Example
Select parsename(replace(t2.code,'_','.'),1)
From YourTable

TSQL extract part of string with regex

i would make a script that iterate over the records of a table with a cursor
and extract from a column value formatted like that "yyy://xx/bb/147011"
only the final number 147011and to put this value in a variable.
It's possible to do something like that?
Many thanks.
You don't need a cursor for this. You can just use a query. The following gets everything after the last /:
select right(str, charindex('/', reverse(str)) - 1 )
from (values ('yyy://xx/bb/147011')) v(str)
It does not specifically check if it is a number, but that can be added as well.
You can also use the below query.
SELECT RIGHT(RTRIM('yyy://xx/bb/147011'),
CHARINDEX('/', REVERSE('/' + RTRIM('yyy://xx/bb/147011'))) - 1) AS LastWord
If numeric value has exact position defined with sample data, then you can do :
SELECT t.*, SUBSTRING(t.col, PATINDEX('%[0-9]%', t.col), LEN(t.col))
FROM table t;

Select column data between () parantheses

I have data in SQL server database column like the following:
Column
Ot ntri - Non Cash - (6932)
Otr Contri- Cash - (6930)
anth C-Cash - (6935)
Phil Cor-Non Cash - (6937)
Poll Conh - (6940)
I need a query to select data that is present only withing the parantheses ().
Please help:
I need to select only
6932
6930
6935
etc for the column
Thanks
A combination of SUBSTRING and CHARINDEX could do this for you:
SELECT * ,
REVERSE(t.[Column]) AS Reversed ,
CASE WHEN t.[Column] LIKE '%(%'
AND t.[Column] LIKE '%)%'
THEN REVERSE(SUBSTRING(REVERSE(t.[Column]),
CHARINDEX(')', REVERSE(t.[Column])) + 1,
CHARINDEX('(', REVERSE(t.[Column]))
- CHARINDEX(')', REVERSE(t.[Column])) - 1))
ELSE NULL
END AS result
FROM dbo.[Table] AS t
I know you have accepted a good answer. This is another way of doing it. Same functions are used with CTE:
SQL server 2008 fiddle example to get the string within last brackets.
;with cte as (
select col, charindex(')',reverse(col),1) brk1,
charindex('(',reverse(col),1) brk2
from t
)
select col, reverse(substring(reverse(col),brk1+1,brk2-brk1-1)) mystr
from cte

extract characters using delimiters

I am having string called '200_CFL_2010'. I wish to get the characters between _'s. I want the output as 'CFL'. I have to achieve it through SQL.
I think this may be dependent on your Database (MySQL, Oracle, whatever..)
Do a search for "string functions" and your database name. For e.g MySQL, you can find it here: http://dev.mysql.com/doc/refman/5.1/en/string-functions.html.
The function INSTR and SUBSTR are the ones you are looking for. Use then like
SELECT SUBSTR(field, INSTR(field, "_", 1), INSTR(field, "_", 2) - INSTR(field, "_", 1)) FROM ...
Note: INSTR does only have two parameters in MySQL... youd need to cascade SUBSTRs a little there.
select substring(col, 0, LEN(col) - charindex('_', col)) as col
from
(
select substring(col, charindex('_', col) + 1, LEN(col)) as col
from
(
select '200_CFL_2010' as col
) as subq
) as subq