SQL functions (String Selection) - sql

I/P : P-2120-001-A10 I need O/p As P-2120 using SQL Server Functions.
this is the given string 'P-2120-001-A10' and i need to select data from given string left of the second '-' symbol i.e 'P-2120' its should select dynamically

Whilst it isn't clear what you are asking for this will transform I/P : P-2120-001-A10 into O/p As P-2120
with sample as (
select 'I/P : P-2120-001-A10' as astring
)
select
substring(astring,7,6) AS guess1
, 'O/p As ' + substring(astring,7,6) AS guess2
from sample

After your Question edit, you could use SUBSTRING & CHARINDEX Function to read the data from string left of the second '-' symbol Dynamically.
SELECT SUBSTRING(<I/P>, 1, CHARINDEX('-', <I/P>)-1)+'-'+SUBSTRING(SUBSTRING(<I/P>, CHARINDEX('-', <I/P>)+1, LEN(<I/P>)), 1, CHARINDEX('-', SUBSTRING(<I/P>, CHARINDEX('-', <I/P>)+1, LEN(<I/P>)))-1);
Output :
P-2120

Related

SQL: What are phone number formatting options?

SQL: What are phone number formatting options?
I query my SQL Database for a phone number:
816-123-4567
I want to output it is as:
816 123-4567.
What steps do I take to achieve this result in an SQL environment?
A standard SQL solution would be:
select substring(phone, 1, 3) || ' ' || substring(phone, 5, 8)
There may be simpler solutions in other databases. For instance, in SQL Server:
select stuff(phone, 4, 1, ' ')
And in MySQL:
select insert(phone, 4, 1, ' ')
Note: These are specific the the format you have provided in your question. If you have other formats, then you might need more complicated logic.
Use SUBSTRING and CHARINDEX functions.
SUBSTRING gets a part of the string according to given indexes.
CHARINDEX gets the index of the character that triggers your String separation.
Below is an MSSQL Server query.
According to your DBMS, the function names can vary, but the logic will is the same.
Query :
SELECT
SUBSTRING('816-123-4567', 0, CHARINDEX('-', '816-123-4567') ) +
' ' +
SUBSTRING('816-123-4567', CHARINDEX('-', '816-123-4567') + 1 , LEN('816-123-4567') -
CHARINDEX('-', '816-123-4567') )
And the result :
816 123-4567
When we put your field and table name instead of static values :
SELECT
SUBSTRING(YourPhoneField, 0, CHARINDEX('-', YourPhoneField) ) +
' ' +
SUBSTRING(YourPhoneField, CHARINDEX('-', YourPhoneField) + 1 , LEN(YourPhoneField) -
CHARINDEX('-', YourPhoneField) )
FROM YourTableName

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;

SQL server Rex fetch string in wildcard

For example, I have got a string with table name and the schema like:
[dbo].[statistical]
How can fetch just the table name statistical out from this string?
This is what PARSENAME is used for:
SELECT PARSENAME('[dbo].[statistical]', 1)
SELECT PARSENAME('[adventureworks].[dbo].[statistical]', 1)
SELECT PARSENAME('[adventureworks]..[statistical]', 1)
SELECT PARSENAME('[statistical]', 1)
SELECT PARSENAME('dbo.statistical', 1)
-- all examples return 'statistical'
You could alternatively try this:
declare #s varchar(100) = 'asd.stadfa';
select reverse(substring(s, 1, charindex('.', s) - 1)) from (
select reverse(#s) s
) a
charindex returns first occurence of character, so you reverse initial string to make last dot first. Then you just use substring to extract first part of reversed string, which is what you are looking for. Finally, you need to apply reverse one more time to reverse back extracted string :)

Trying to extract number between 2 characters '|' MS SQL

I have column and need to extract number between 2 pipes |, example data inside is AAA|12345678|#RRR. I need to get this number 12345678.
my code is:
SELECT SUBSTRING(column_name,CHARINDEX('|',column_name) + 1, CHARINDEX('|',column_name) - CHARINDEX('|',column_name) - 1)
FROM [name].[name].[table_name]
Using your own code:
SELECT SUBSTRING(column_name,CHARINDEX('|',column_name) + 1,
CHARINDEX('|',column_name) - CHARINDEX('|',column_name) - 1)
FROM [name].[name].[table_name]
The second part of substring is not correct. It should be:
SELECT SUBSTRING(column_name,CHARINDEX('|',column_name) + 1,
CHARINDEX('|',column_name, CHARINDEX('|',column_name)))
FROM [name].[name].[table_name]
The nested CHARINDEX will look for the position of the second pipe. and the SUBSTRING will start from the first pipe and continue to the second
Assuming the 2nd position, you can use a little XML or ParseName()
XML Example
Declare #YourTable table (ID int,column_name varchar(max))
Insert Into #YourTable values
(1,'AAA|12345678|#RRR')
Select ID
,SomeValue = Cast('<x>' + replace(column_name,'|','</x><x>')+'</x>' as xml).value('/x[2]','varchar(max)')
From #YourTable
ParseName() Example
Select ID
,SomeValue = parsename(replace(column_name,'|','.'),2)
From #YourTable
Both would Return
ID SomeValue
1 12345678
String extraction is generally tricky in SQL Server. But if you only have one numeric value and are looking for it, then the code isn't that bad:
select patindex('%[0-9]|%', str),
substring(str, patindex('%|[0-9]%', str), patindex('%[0-9]|%', str) - patindex('%|[0-9]%', str) + 1)
from (values ('AAA|12345678|#RRR')) v(str)
I would use PARSENAME() :
select parsename(replace(str, '|', '.'), 2)
from ( values ('AAA|12345678|#RRR')
) v(str);

Substring with conditional statement

tl;dr
I don't understand how to conditionally change the length parameter of SUBSTRING(..)
Short enough, did read
I've got a text field in a sql table that I want to retrieve a substring from
There is a specific part of text I am having trouble retrieving a substring from, because I cannot guarantee the next string.
For example, I have:
... Tracking Code : /a/delimited/string AttributeW : ValueW ...
And
... Tracking Code : /a/different/delimited/string A random string ...
From both of those i want /a/delimited/string and /a/different/delimited/string respectively
My current sql looks something like:
DECLARE #TrackingStartStr VARCHAR(50), #TrackingEndStr VARCHAR(50)
SET #TrackingStartStr = 'Tracking Code :'
SET #TrackingEndStr = 'Some string that indicates the text is about to end'
SELECT
AField
,RTRIM(LTRIM(Substring(CAST([Body] AS VARCHAR(MAX))
,Charindex(#TrackingStartStr,CAST([Body] AS VARCHAR(MAX))) + LEN(#TrackingStartStr)
,charindex(#TrackingEndStr,CAST([Body] AS VARCHAR(MAX))) - (Charindex(#TrackingStartStr,CAST([Body] AS VARCHAR(MAX))) + LEN(#TrackingStartStr))
))) AS TrackingCode
From tbl_stupidTextTable
I don't know how to conditionally change what #TrackingEndStr is for each row.
Try:
select substring(stringfield,
charindex('/', stringfield, 1),
charindex(' ',
stringfield,
charindex('/', stringfield, 1)) -
charindex('/', stringfield, 1)) as val
from tbl
SQL Fiddle demo: http://sqlfiddle.com/#!6/cebab/16/0