Parse URL in SQL Server

Hello everyone,

In this article, I will give information about URL parsing in SQL Server.

In SQL Server you may want to parse the URL in some cases.

Let me explain what I mean. Have a URL address like the one below.

https://www.example.com/?utm_source=google&utm_medium=blabla&utm_campaign=gameuser&utm_term=winwin&utm_content=takego

We will parse this URL address as follows.

Parse URL in SQL Server

You can easily do this using the function below.

CREATE FUNCTION dbo.ParseQueryString (@url NVARCHAR(MAX))
RETURNS @Result TABLE (
	[Name] NVARCHAR(255)
   ,[Value] NVARCHAR(255)
)
AS
BEGIN
	DECLARE @questionIndex INT = charindex('?', @url)
	DECLARE @queryString NVARCHAR(MAX) = NULL
	DECLARE @startPosition INT = 1
	DECLARE @endPosition INT = 1
	DECLARE @name NVARCHAR(255) = NULL
	DECLARE @value NVARCHAR(255) = NULL

	IF @questionIndex > 0
	BEGIN
		SET @queryString = substring(@url, @questionIndex + 1, LEN(@url))
		SET @startPosition = 1
		SET @endPosition = charindex('&', @queryString)

		WHILE @endPosition > 0
		BEGIN
		SET @name = substring(@queryString, @startPosition, charindex('=', @queryString, @startPosition) - @startPosition)
		SET @value = substring(@queryString, charindex('=', @queryString, @startPosition) + 1, @endPosition - charindex('=', @queryString, @startPosition) - 1)
		INSERT INTO @Result ([Name], [Value])
			VALUES (@name, @value)

		SET @startPosition = @endPosition + 1
		SET @endPosition = charindex('&', @queryString, @startPosition)
		END

		SET @name = substring(@queryString, @startPosition, charindex('=', @queryString, @startPosition) - @startPosition)
		SET @value = substring(@queryString, charindex('=', @queryString, @startPosition) + 1, LEN(@queryString) - charindex('=', @queryString, @startPosition))
		INSERT INTO @Result ([Name], [Value])
			VALUES (@name, @value)
	END

	RETURN
END

--Kullanımı

SELECT
	*
FROM dbo.ParseQueryString('https://www.example.com/?utm_source=google&utm_medium=blabla&utm_campaign=gameuser&utm_term=winwin&utm_content=takego')

When you create and run the above function, you will see a result similar to the one below.

Parse URL in SQL Server

As you can see, we have parsed the URL.

Good luck to everyone in business and life.

35 Views

Yavuz Selim Kart

I try to explain what I know in software and database. I am still improving myself by doing research on many programming languages. Apart from these, I am also interested in Graphic Design and Wordpress. I also have knowledge about SEO and Social media management. In short, I am a determined person who likes to work hard.

You may also like...

Don`t copy text!