Stripping a specific part of variable in SQL - sql

I have a variable where i dynamically store the URL
For Eg. a="https://myaccessdev.searshc.com/aveksa/main?Oid=1&ReqType=GetPage&ObjectClass=com.aveksa.gui.objects.workflow.GuiWorkflowJob&WFObjectID=3478:WPDS"
I want to strip the number in the last before ":WDPS" from this whole string.
Is there any way of doing it in SQL

I want to strip the number [...] before ":WDPS" from this whole string.
This is a perfect match for REGEXP_REPLACE:
with test_data as
(select 'https://myaccessdev.searshc.com/aveksa/main?Oid=1&ReqType=GetPage&ObjectClass=com.aveksa.gui.objects.workflow.GuiWorkflowJob&WFObjectID=3478:WPDS' str
from dual)
select REGEXP_REPLACE(str, '.*=([0-9]*):WPDS.*', '\1') from test_data
-- ^^^^^^^^^^^^^^^^^^^^ ^^^^
-- replace everything before and after by the first capturing
-- the target string group (i.e.: the sequence between
-- parenthesis in the regular expression)
Producing:
3478
See http://sqlfiddle.com/#!4/d41d8/37095 for a live demo.

If you just want the number, you can do something like this:
select regexp_substr(regexp_substr(s, '=[0-9]*:WPDS', 1, 1), '[0-9]*', 1, 1)
You can do this with regexp_substr(). I'm having trouble testing it right now. The following comes quite close:
select regexp_substr(s, '=[0-9]*:WPDS', 1, 1)

Try this
DECLARE #string varchar(255) = 'https://myaccessdev.searshc.com/aveksa/main?Oid=1&ReqType=GetPage&ObjectClass=com.aveksa.gui.objects.workflow.GuiWorkflowJob&WFObjectID=3478:WPDS'
DECLARE #end varchar(10) = REVERSE(SUBSTRING(REVERSE(#string),0,CHARINDEX('=', REVERSE(#string))))
SELECT SUBSTRING(#end,0,CHARINDEX(':', #end))

Related

Trimming value from a column in Snowflake

I have column called File with values 'Mens_Purchaser_Segment_Report' and 'Loyalist_Audience_Segment_Report'. I want to capture everything that comes before word Segment.
I used query:
select
TRIM(file,regexp_substr(file, '_Segment_Report.*')) as new_col
Output:
Mens_Purch
Loyalist_Audi
How do I capture everything before Segment?
Tried below but same results-->
TRIM(file,regexp_substr(file, 'S.*'))
TRIM(file,regexp_substr(file, '_S.*'))
You didn't specify if the trailing text is always _Segment_Report, you're asking for any text before _Segment. Depending on that various solutions can be used, see below.
create or replace table foo(s string) as select * from values
('Mens_Purchaser_Segment_Report'),
('Loyalist_Audience_Segment_Report');
-- If you know the suffix you want to remove is always exactly '_Segment_Report'
select s, replace(s, '_Segment_Report', '') from foo;
-- If you know the suffix you want to remove starts with '_Segment' but can have something after
-- - approach 1, where we replace the _Segment and anything after it with nothing
select s, regexp_replace(s, '_Segment.*', '') from foo;
-- - approach 2, where we extract things before _Segment
-- Note: it will behave differently if there are many instances of '_Segment'
select s, regexp_substr(s, '(.*)_Segment.*', 1, 1, 'e') from foo;
try
using regexp_replace
select regexp_replace(fld1, 'Segment', '') from (
select 'Mens_Purchaser_Segment_Report and Loyalist_Audience_Segment_Report' fld1 from dual );

Regex: how to get the text between a few colons?

So, i have a lot of strings like the ones below in my database:
product1:1stparty:single_aduls:android:
product2:3rdparty:married_adults:ios:
product3:3rdparty:other_adults:android:
I need a regex to get only the text after the product name and before the device category. So, in the first line I'd get 1stparty:single_aduls, in the second 3rdparty:married_adults and in the third 3rdparty:other_adults. I'm stuck and can't find a way to solve that. Could anyone help me please?
As a regular expression, you can use:
select regexp_extract('product1:1stparty:single_aduls:android:', '^[^:]*:(.*):[^:]*:$')
This returns every after the first colon and before the penultimate colon.
We can try using REGEXP_REPLACE here:
SELECT REGEXP_REPLACE(val, r"^.*?:|:[^:]+:$", "") AS output
FROM yourTable;
This approach removes either the leading ...: or trailing :...: from the column, leaving behind the content you want. Here is a demo showing that the regex replacement is working:
Demo
You can also use standard split function and access result array element by index, which is quite clear to read and understand.
with a as (
select split('product1:1stparty:single_aduls:android:', ':') as splitted
)
select splitted[ordinal(2)] || ':' || splitted[ordinal (3)] as subs
from a
Consider below example
with your_table as (
select 'product1:1stparty:single_aduls:android:' txt union all
select 'product2:3rdparty:married_adults:ios:' union all
select 'product3:3rdparty:other_adults:android:'
)
select *,
(
select string_agg(part, ':' order by offset)
from unnest(split(txt, ':')) part with offset
where offset in (1, 2)
) result
from your_table
with output

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 :)

TSQL How to get the 2nd number from a string

We have the below in row in MS SQL:
Got event with: 123.123.123.123, event 34, brown fox
How can we extract the 2nd number ie the 34 reliable in one line of SQL?
Here's one way to do it using SUBSTRING and PATINDEX -- I used a CTE just so it wouldn't look so awful :)
WITH CTE AS (
SELECT
SUBSTRING(Data,CHARINDEX(',',Data)+1,LEN(Data)) data
FROM Test
)
SELECT LEFT(SUBSTRING(Data, PATINDEX('%[0-9]%', Data), 8000),
PATINDEX('%[^0-9]%',
SUBSTRING(Data, PATINDEX('%[0-9]%', Data), 8000) + 'X')-1)
FROM CTE
And here is some sample Fiddle.
As commented, CTEs will only work with 2005 and higher. If by chance you're using 2000, then this will work without the CTE:
SELECT LEFT(SUBSTRING(SUBSTRING(Data,CHARINDEX(',',Data)+1,LEN(Data)),
PATINDEX('%[0-9]%', SUBSTRING(Data,CHARINDEX(',',Data)+1,LEN(Data))), 8000),
PATINDEX('%[^0-9]%',
SUBSTRING(SUBSTRING(Data,CHARINDEX(',',Data)+1,LEN(Data)),
PATINDEX('%[0-9]%', SUBSTRING(Data,CHARINDEX(',',Data)+1,LEN(Data))), 8000) + 'X')-1)
FROM Test
Simply replace #s with your column name to apply this to a table. Assuming that number is between last comma and space before the last comma. Sql-Fiddle-Demo
declare #s varchar(100) = '123.123.123.123, event 34, brown fox'
select right(first, charindex(' ', reverse(first),1) ) final
from (
select left(#s,len(#s) - charindex(',',reverse(#s),1)) first
--from tableName
) X
OR if it is between first and second commas then try, DEMO
select substring(first, charindex(' ',first,1),
charindex(',', first,1)-charindex(' ',first,1)) final
from (
select right(#s,len(#s) - charindex(',',#s,1)-1) first
) X
I've thought of another way that's not been mentioned yet. Presuming the following are true:
Always one comma before the second "part"
It's always the word "event" with the number in the second part
You are using SQL Server 2005+
Then you could use the built in ParseName function meant for parsing the SysName datatype.
--Variable to hold your example
DECLARE #test NVARCHAR(50)
SET #test = 'Got event with: 123.123.123.123, event 34, brown fox'
SELECT Ltrim(Rtrim(Replace(Parsename(Replace(Replace(#test, '.', ''), ',', '.'), 2), 'event', '')))
Results:
34
ParseName parses around dots, but we want it to parse around commas. Here's the logic of what I've done:
Remove all existing dots in the string, in this case swap them with empty string.
Swap all commas for dots for ParseName to use
Use ParseName and ask for the second "piece". In your example this gives us the value
" event 34".
Remove the word "event" from the string.
Trim both ends and return the value.
I've no comments on performance vs. the other solutions, and it looks just as messy. Thought I'd throw the idea out there anyway!

T-SQL Substring - Last 3 Characters

Using T-SQL, how would I go about getting the last 3 characters of a varchar column?
So the column text is IDS_ENUM_Change_262147_190 and I need 190
SELECT RIGHT(column, 3)
That's all you need.
You can also do LEFT() in the same way.
Bear in mind if you are using this in a WHERE clause that the RIGHT() can't use any indexes.
You can use either way:
SELECT RIGHT(RTRIM(columnName), 3)
OR
SELECT SUBSTRING(columnName, LEN(columnName)-2, 3)
Because more ways to think about it are always good:
select reverse(substring(reverse(columnName), 1, 3))
declare #newdata varchar(30)
set #newdata='IDS_ENUM_Change_262147_190'
select REVERSE(substring(reverse(#newdata),0,charindex('_',reverse(#newdata))))
=== Explanation ===
I found it easier to read written like this:
SELECT
REVERSE( --4.
SUBSTRING( -- 3.
REVERSE(<field_name>),
0,
CHARINDEX( -- 2.
'<your char of choice>',
REVERSE(<field_name>) -- 1.
)
)
)
FROM
<table_name>
Reverse the text
Look for the first occurrence of a specif char (i.e. first occurrence FROM END of text). Gets the index of this char
Looks at the reversed text again. searches from index 0 to index of your char. This gives the string you are looking for, but in reverse
Reversed the reversed string to give you your desired substring
if you want to specifically find strings which ends with desired characters then this would help you...
select * from tablename where col_name like '%190'