0

I'm trying to parse information from a column of URLS in SQL Server 2012

The basic structure is

http://www.domainsomething.com/?test/campaign=abc&kwd=jdc ftp&catgory=brnd

Where I need to grab the parameters from the kwd= value. In the above example, it would be the 'jdc ftp', but this would might be different for all the URLs in my column. I've tried CHARINDEX and LEN, but I can't seem to put the syntax together correctly.

2
  • Show your "failing" code Commented Jun 28, 2015 at 8:22
  • This is really not something you want to be doing in SQL Server. In a good design the client application could be anything, not just a web application. You should not have to go down to the guts of HTML in your SQL code - separate it out into the parameters you expect and let the calling code sort it out. Commented Jun 28, 2015 at 11:05

1 Answer 1

1

Try this:

DECLARE @URL varchar(100) = 'http://www.domainsomething.com/?test/campaign=abc&kwd=jdc ftp&catgory=brnd'

SELECT SUBSTRING(
       @URL, 
       CHARINDEX('kwd=', @URL)+4, 
       CASE WHEN CHARINDEX('&', @URL, CHARINDEX('kwd=', @URL)+5) > 0 THEN
       CHARINDEX('&', @URL, CHARINDEX('kwd=', @URL)+5)
        - (CHARINDEX('kwd=', @URL)+4)
       ELSE
          LEN(@URL)
       END
       )

This will also handle cases when the kwd is the last or first variable in the query string.

You can play with it yourself in this sql fiddle.

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

2 Comments

I suggest CHARINDEX('kwd=', @URL + 'kwd=')+4 to return '' for a URL that has no kwd= ;)
@shA.t That might be a good idea, but it is dependent on business logic. I was going on the assumption that a url without a kwd parameter should raise an error.

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.