简体   繁体   English

查询同一个表以获取MS SQL Server中的数据库列表

[英]Querying the same table for a list of databases in MS SQL Server

This is my first time posting on SO, so please go easy! 这是我第一次发布SO,所以请放心!

I'm attempting to write a SQL script that queries the same table for a list of databases in a single SQL Server instance. 我正在尝试编写一个SQL脚本,该脚本在同一个表中查询单个SQL Server实例中的数据库列表。

I have successfully queried the list of databases that I required using the following, and inserting this data into a temp table. 我已经使用以下内容成功查询了我需要的数据库列表,并将此数据插入到临时表中。

Select name Into #Versions
From sys.databases
Where name Like 'Master%'

Master is suffixed with numerical values to identify different environments. Master用数值后缀以标识不同的环境。

Select * From #Versions

Drop Table #Versions

The table name I am trying to query, is the same in each of the databases, and I want to extract the newest value from this table and insert it into the temp table for each of the database names returned. 我试图查询的表名在每个数据库中是相同的,我想从该表中提取最新值,并将其插入temp表中以返回每个返回的数据库名称。

I have tried researching this but to no avail. 我试过研究这个但无济于事。 I am fairly comfy with SQL but I fear I could be out of my depth here. 我对SQL很满意,但我担心这可能会超出我的深度。

You can do the following. 您可以执行以下操作。 Once you have the list of your databases, you can build up the query (you need to edit it for your purpose). 获得数据库列表后,可以构建查询(需要根据自己的需要对其进行编辑)。

Select name Into #Versions
From sys.databases
Where name Like 'test%'

declare @sql as varchar(max) = ''
select @sql = @sql + 'INSERT INTO sometable SELECT TOP 1 * FROM ' + name + '..sourcetable ORDER BY somedate DESC; '
FROM #Versions

exec (@sql)

Drop Table #Versions

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM