July 13, 2020 at 4:32 pm
How to find the last occurrence of '\' in the following string and get left part of it?
DECLARE @v-2 VARCHAR(max)='O:\Z\P_Metrics\Inbox\07-13-20200702_abc_enroll.csv'
DECLARE @V1 VARCHAR(max)='O:\Z\P_Metrics\Inbox\07-14-20200702_abc_complete_enroll.csv'
The Final output I need is O:\Z\P_Metrics\Inbox.
Thanks in advance.
July 13, 2020 at 4:52 pm
What version of T-SQL are you actually using? I ask because there's no such thing as "VARCHR" in T-SQL. There is "VARCHAR" but it has two "A"s in it instead of just 1.
--Jeff Moden
Change is inevitable... Change for the better is not.
July 13, 2020 at 5:03 pm
If your file names always follow that consistent pattern, you could use something like this:
DECLARE @v VARCHAR(MAX) = 'O:\Z\P_Metrics\Inbox\07-13-20200702_abc_enroll.csv';
DECLARE @V1 VARCHAR(MAX) = 'O:\Z\P_Metrics\Inbox\07-14-20200702_abc_complete_enroll.csv';
SELECT LEFT(@v, PATINDEX('%[0-9][0-9]-[0-9][0-9]-%', @v) - 2);
SELECT LEFT(@V1, PATINDEX('%[0-9][0-9]-[0-9][0-9]-%', @V1) - 2);
Your (more expensive) alternative is to use a combination of REVERSE(), CHARINDEX(), LEN() and LEFT().
The absence of evidence is not evidence of absence
- Martin Rees
The absence of consumable DDL, sample data and desired results is, however, evidence of the absence of my response
- Phil Parkin
July 13, 2020 at 5:26 pm
Phil has good advice. If the patterns aren't consistent, then use REVERSE and find the first occurrence.
July 13, 2020 at 6:42 pm
DECLARE @v VARCHAR(100)='O:\Z\P_Metrics\Inbox\07-13-20200702_abc_enroll.csv';
DECLARE @V1 VARCHAR(100)='O:\Z\P_Metrics\Inbox\07-14-20200702_abc_complete_enroll.csv';
Solution:
SELECT LEFT(@V1,LEN(@V1) - CHARINDEX('\',REVERSE(@V1),1))
Returns:
O:\Z\P_Metrics\Inbox
O:\Z\P_Metrics\Inbox
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply