0

I have this fields in a SQL Table

[header]nombre=LPP Expreso LD Santiago 2 Descargas-01-10-2007 codigo=ACGRZ target=0 activo=0
[header]nombre=BS.AS / ORAN 01-07-2019 codigo=ACJEX target=0 activo=1 VigenciaDesde=01/07/2019
[header]nombre=ATC Cargas MZA/TUC/SGO.TN.03/03/10 DEV codigo=ACLGO target=0 activo=1 VigenciaD

How can i do a query to get the String: codigo=XXXXXX ? The text codigo is always in a diferente position

2
  • Your question is unclear. What is your table structure and what are you trying to do? Commented Oct 21, 2019 at 16:40
  • If this is the data in your table, then there is something very wrong with your database design. Commented Oct 21, 2019 at 16:44

2 Answers 2

1

SQL Server has poor string processing functionality. That is why it is better to process data when it goes into the database.

That said, you can do what you want. Here is one method:

select t.*, left(v1.str, charindex(' ', v1.str + ' ')) as codigo_str
from (values ('[header]nombre=ATC Cargas MZA/TUC/SGO.TN.03/03/10 DEV codigo=ACLGO target=0 activo=1 VigenciaD')) t(str) cross apply
     (values (stuff(t.str, 1, charindex('codigo=', t.str + 'coldigo=') - 1, ''))) v1(str);

This chops off the string before the 'codigo='. It then uses left() to take everything up to the first space.

The use of concatenation within charindex() makes this safe if 'codigo=' is not in the string or not followed by a space.

Sign up to request clarification or add additional context in comments.

2 Comments

It works writing the string like you posted, but how can i apply it to a Column for example?
@LopezLopez . . . I have no idea what you are asking in your comment. In this query, the column name is str. You can use whatever name you like.
0

Play around SQL built in functions, CHARINDEX and SUBSTRING. Logically, the following pseudocode should work:

  1. Get the index where your keyword is placed alongside your entire string.
  2. From index, add the number or lenght of characters you used from your keyword.
  3. Substring the entire text from result of step number 2 up until to the number of desired lenght of text. If you're text is fixed then it would be easier.

See CHARINDEX and SUBSTRING.

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.