May 2, 2014 at 12:16 pm
In t-sql 2008 r2, I would like to know how to select a specific string in a varchar(50) field. The field in question is called 'CalendarId'.
This field can contain values like:
xxIN187 13-14 W Elem
HS321 13-14 D Elem
IN636 13-14 C Elem
030 13-14 clark middle.
What I am looking for is the first position that contains a number value for the length of 3. Thus what I want are values that look like the following: 030, 636, 187.
What I know that I want is substring(CalendarId,?,3).
The question mark is where I want the starting location of a number value (0 to 9) of the value in CalendarId . I tried pathindex but my syntax did not work.
Thus can you show me the t-sql that will solve my problem?
May 2, 2014 at 12:39 pm
Are you looking for something like this? Or what is your expected output?
WITH SampleData AS(
SELECT 'xxIN187 13-14 W Elem' CalendarId UNION ALL
SELECT 'HS321 13-14 D Elem' UNION ALL
SELECT 'IN636 13-14 C Elem' UNION ALL
SELECT '030 13-14 clark middle.'
)
SELECT *, PATINDEX('%[0-9][0-9][0-9]%', CalendarId)
FROM SampleData
May 2, 2014 at 12:39 pm
I believe you are looking for CHARINDEX with [0-9][0-9][0-9].
Something like:
SUBSTRING(yourvalue, CHARINDEX('[0-9][0-9][0-9]',yourvalue), lengthyourvalue)
Note this is not tested.
May 2, 2014 at 12:44 pm
djj (5/2/2014)
I believe you are looking for CHARINDEX with [0-9][0-9][0-9].Something like:
SUBSTRING(yourvalue, CHARINDEX('[0-9][0-9][0-9]',yourvalue), lengthyourvalue)
Note this is not tested.
CHARINDEX doesn't accept wildcards, that why we need to use PATINDEX.
May 2, 2014 at 12:46 pm
Thanks Lois. I said it was not tested. 😀
That is two wrong in about ten minutes. Time to go home.
May 2, 2014 at 1:59 pm
When I try: PATINDEX('%[0-9][0-9][0-9]%', CalendarId), I get the error message, "Msg 8116, Level 16, State 1, Line 2
Argument data type int is invalid for argument 2 of patindex function."
Thus can you tell me what else you would try to use?
May 2, 2014 at 2:07 pm
You could start by posting the correct information. The values that you posted can't be stored in an int column. You have either the incorrect column or the incorrect logic. I can't guess on this one.
Viewing 7 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply