The current database name is available within the SQL interface as
SELECT DB_NAME() AS [Current Database]
with the set of possible database names available from
SELECT name
FROM Sys.Databases
WHERE database_id >5
ORDER BY name
However, these database names typically return in the form StackExchange.Math.Meta
, which is the domain name, minus the .com, in reverse.
One way to reverse them to create a proper URL is to use
DECLARE @sitexml XML, @site VARCHAR(100)
SET @sitexml = CAST(('<X>' + REPLACE((SELECT DB_NAME() AS [Current Database]), '.', '</X><X>') + '</X>') AS XML)
SET @site=LOWER(STUFF((SELECT '.' + C.value('.', 'VARCHAR(50)')
FROM @sitexml.nodes('X') AS X(C)
ORDER BY ROW_NUMBER() OVER (ORDER BY (SELECT 0)) DESC
FOR XML PATH('')), 1, 1, ''))+'.com'
SELECT
'http://'+@site+'/posts/'+CAST(Id AS varchar)+'/timeline|timeline' AS 'Timeline link'
FROM Posts
WHERE ...
I remain interested in cleaner ways to do this, though.
In addition to that, there's another place where you might want the current database name, and that's if you're linking to other queries within the data explorer. This can be done with the following adaptation of the above:
DECLARE @siteinit VARCHAR(100), @site VARCHAR(100)
SET @siteinit=REPLACE(LOWER( (SELECT DB_NAME() AS [Current Database]) ),'StackExchange.','')
SET @site = REPLACE(REPLACE(REPLACE( --REPLACE(
CASE
WHEN @siteinit NOT LIKE '%.Meta' THEN @siteinit
ELSE 'meta.'+REPLACE(@siteinit,'.Meta','')
END
,'audio','avp') ,'stackoverflow.br','stackoverflow.pt') ,'stackoverflow.','')
--,'meta.','')+'me' -- Some meta sites require this
SELECT TOP 1
@site AS 'handle',
'https://data.stackexchange.com/'+@site AS 'SEDE home',
'https://data.stackexchange.com/'+@site+'/query/516017' AS 'This query'
FROM PostTypes
available at The current site's SEDE database handle for query URLs, or for an overall view at All site handles for SEDE query URLs.
Note in particular the inconsistent URL usage for meta sites: it's academia and meta.academia but it can sometimes be arduino and arduinome.