2

I want to get base url from CompleteURL using sql.

Example: completeUrl: SELECT INTO Variable in MySQL DECLARE causes syntax error?. I want get :https://stackoverflow.com/

select left(CompleteURL, charindex('/', CompleteURL, charindex('://', CompleteURL ) + 3 )  - 1 )
from urls2;
2
  • What database are you using? The syntax in that answer is neither MySQL nor Oracle. Commented Apr 11, 2016 at 13:33
  • Do you have any specific question about this? Commented Apr 2, 2024 at 12:58

1 Answer 1

-1

Using sql server you can use a combination of patindex and substring.

create or alter function dbo.fnGetBaseUrlFromPath(@vchURL varchar(1000), @bIncludeTrailingSlash bit)
returns varchar(1000)
as
begin
    declare @BaseURL varchar(1000)

select @BaseURL = 
        substring(
            @vchURL, 
            1, 
            case 
                when @vchURL like '%[A-Za-z][/?][A-Za-z]%' then patindex('%[A-Za-z][/?][A-Za-z]%',@vchURL) + case when @bIncludeTrailingSlash = 1 then 1 else 0 end
                else len(@vchURL) 
            end
        )
    return @BaseURL
end 
go

select dbo.fnGetBaseUrlFromPath('https://stackoverflow.com/questions/36550145/get-base-url-from-completeurl-using-sql', 1)
select dbo.fnGetBaseUrlFromPath('https://stackoverflow.com', 0)
select dbo.fnGetBaseUrlFromPath('https://stackoverflow.com/', 0)
select dbo.fnGetBaseUrlFromPath('https://stackoverflow.com?somequeryparam=123', 0)
Sign up to request clarification or add additional context in comments.

2 Comments

"Using sql server" is not matching the main tag mysql from the original questino
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

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.