从动态SQL获取数据库名称的名称

时间:2019-02-11 10:28:00

标签: sql-server tsql

我有两个服务器,都包含多个具有相同表的数据库。

我用两列创建一个临时表:ServerName和DBName。使用该代码,我可以使用下面的SQL来获取我需要的所有行。

但是我需要一列来显示每行从哪个数据库返回。

可能这是一种非常简单的方法,使我难以理解。

尝试使用db_name()-给我执行数据库的名称。 试过使用我的模板,但由于没有加入,所以得到了笛卡尔积。

set @SQL = STUFF((SELECT   '

UNION ALL

 ' + 'SELECT terminalname,path,SID as tillnumber, AlternateName , CASE WHEN 
 thyronremoteport = 29000 then ''Wired'' WHEN thyronremoteport = 25000 then 
''Wireless'' else ''Unknown'' end as ped

 FROM ' + quotename(SERVERNAME)  + '.' + quotename (dbname) +        
'.dbo.TerminalStats where LEN(terminalname) = 5 and substring(terminalname, 
 1,1) = ''T'''

FROM  #tempDBNames 

FOR XML PATH(''), type).value('.','varchar(max)'),1,15,'')

print (@SQL)

execute(@SQL)

因此,上面查询的结果是下面动态创建的SQL,该语句按照以下内容继续对约20个数据库进行操作。

SELECT terminalname,path,SID as tillnumber, AlternateName , CASE WHEN 
thyronremoteport = 29000 then 'Wired' WHEN thyronremoteport = 25000 then 
'Wireless' else 'Unknown' end as ped

 FROM [Server1].[db1].dbo.TerminalStats where LEN(terminalname) = 5 
 and substring(terminalname, 1,1) = 'T'

 UNION ALL

SELECT terminalname,path,SID as tillnumber, AlternateName , CASE WHEN 
thyronremoteport = 29000 then 'Wired' WHEN thyronremoteport = 25000 then 
'Wireless' else 'Unknown' end as ped

 FROM [Server2].[db1].dbo.TerminalStats where LEN(terminalname) = 5 and 
 substring(terminalname, 1,1) = 'T'

1 个答案:

答案 0 :(得分:3)

DB_NAME()列表中添加SELECT结果。

set @SQL = STUFF((SELECT   '

UNION ALL

 ' + 'SELECT 
    terminalname,
    path,SID as tillnumber, 
    AlternateName , 
    DB_NAME() as DatabaseName,
    CASE WHEN thyronremoteport = 29000 then ''Wired'' WHEN thyronremoteport = 25000 then ''Wireless'' else ''Unknown'' end as ped

 FROM ' + quotename(SERVERNAME)  + '.' + quotename (dbname) +        
'.dbo.TerminalStats where LEN(terminalname) = 5 and substring(terminalname, 
 1,1) = ''T'''

FROM  #tempDBNames 

FOR XML PATH(''), type).value('.','varchar(max)'),1,15,'')

print (@SQL)

execute(@SQL)

或者只需将表中的名称重复为文字即可。

set @SQL = STUFF((SELECT   '

UNION ALL

 ' + 'SELECT 
    terminalname,
    path,SID as tillnumber, 
    AlternateName , 
    ''' + quotename (dbname) + ''' As DatabaseName,
    CASE WHEN thyronremoteport = 29000 then ''Wired'' WHEN thyronremoteport = 25000 then ''Wireless'' else ''Unknown'' end as ped

 FROM ' + quotename(SERVERNAME)  + '.' + quotename (dbname) +        
'.dbo.TerminalStats where LEN(terminalname) = 5 and substring(terminalname, 
 1,1) = ''T'''

FROM  #tempDBNames 

FOR XML PATH(''), type).value('.','varchar(max)'),1,15,'')

print (@SQL)

execute(@SQL)