In the SqlServer database that I am using, the database name is similar to StackExchange.Audio.Meta or StackExchange.Audio or StackOverflow . By sheer luck, this is also the URL of the website. I only need to break it into points and cancel it: meta.audio.stackexchange . Add http:// and .com , and you're done. Obviously, StackOverflow does not need to do the opposite.
Using SqlServer 2016 string_split function I can easily split and rearrange the result:
select value from string_split(db_name(),'.') order by row_number() over( order by (select 1)) desc
It gives me
| Value | ----------------- | Meta | | Audio | | StackExchange |
Since I need to have a url in a variable, I was hoping to combine it using this answer , so my attempt looks like this:
declare @revname nvarchar(150) select @revname = coalesce(@revname +'.','') + value from string_split(db_name(),'.') order by row_number() over( order by (select 1)) desc
However, this returns me the last value, StackExchange . I already noticed warnings for this answer that this trick only works for certain execution plans, as described here .
The problem is apparently caused by the order by clause. Without this, I get all the values, but then in the wrong order. I tried to add the ltrim and rtrim , as suggested in a Microsoft article, as well as a subquery, but so far with no luck.
Is there any way I can push Query Engine Sql Server 2016 to associate an ordered result with this string_split in a variable?
I know that I can use for XML or even a simple cursor to get the result I need, but I do not want to abandon this elegant solution for now.
When I run this in the stack data explorer, I cannot use the functions, because we lack permission to create them. I can perform Stored Procedures, but I was hoping I could evade them.
I prepared SEDE Query for experimentation. Database names that are expected, either without dots, aka StackOverflow , with 1 dot: StackOverflow.Meta or two dots, `StackExchange.Audio.Meta, a complete list of databases is here