|
|
Question : Understanding charindex used in t-sql
|
|
Hi, Only yesterday i asked for some help in a query to enable me to get part of a string out of a field. I recieved many answers back and this worked the best, however i am relatively new to this and i am finding it difficult to understand the actual working behind the code.
I am hoping someone can explane what is going on here, i was trying to mail this question to the person that wrote this but i can not. Here is an example of the field i gave: For example here are two text fields: Create table customer_history (history_id int not null, customer_id int not null, date_entered datetime not null, history_text text not null)
Insert into customer_history values (1004963,24829, '2007-06-07 15:48:42.000','BILLING INFO CHANGE
| | width=3> | >TO | | bgcolor=#e6e6e6>FROM</tr> d width=3> Bill Day | 25 | > 17 </td> | <tr> | Tax Exempt Expiration Date | 06/2007 | | > 12/1999 ');
Insert into customer_history values (1002583,12345,'2007-06-07 15:48:42.000','BILLING INFO CHANGE
| | width=3> | >TO | | bgcolor=#e6e6e6>FROM</tr> d width=3> Bill Day | 7 | 4 d> | > | Sales Rep | | <td> User, Legacy ble>');
This is the code below:
Declare @SubStringSearch VarChar(200) Declare @SecondaryStringSearch VarChar(200)
Set @SubStringSearch = 'Bill Day ' Set @SecondaryStringSearch = ' | '
Select history_id,customer_id, date_entered, substring( substring(history_text, (charindex(@SubStringSearch,history_text)+ len(@SubStringSearch)) ,5) ,0,charindex('&', substring(history_text, (charindex(@SubStringSearch,history_text)+ len(@SubStringSearch)) ,5))),
substring(substring( substring(history_text, (charindex(@SubStringSearch,history_text)+ len(@SubStringSearch)) ,Len(cast(history_text as VarChar(max))) ),charindex(@SecondaryStringSearch , substring(history_text, (charindex(@SubStringSearch,history_text)+ len(@SubStringSearch)) ,Len(cast(history_text as VarChar(max))))) + len(@SecondaryStringSearch),10 ),0,
charIndex('&',substring( substring(history_text, (charindex(@SubStringSearch,history_text)+ len(@SubStringSearch)) ,Len(cast(history_text as VarChar(max))) ),charindex(@SecondaryStringSearch , substring(history_text, (charindex(@SubStringSearch,history_text)+ len(@SubStringSearch)) ,Len(cast(history_text as VarChar(max))))) + len(@SecondaryStringSearch),10 ))) FROM customer_history
All help greatly appriciated.
Thank you , putoch,
|
|
|
Answer : Understanding charindex used in t-sql
|
|
No there are only 3 parts to a substring -- The Full String, The Starting Position and the Length from the Starting Position.
By adding the ",0" You'll cause a syntax error. If you would like to Check for Null I would Recommend
select IsNull(substring (history_test (charindex (@SubStringSearch,history_text)+ len(@SubStringSearch)) ,5),0)
|
|
|
|
|