我需要从具有相同架构的表的多个数据库中获取数据。为此,我在其中一个数据库中为该表创建了同义词。数据库的数量会随着时间的推移而增长。因此,抓取数据的过程应该是灵活的。我写了下面的代码片段来解决这个问题:
WHILE @i < @count
BEGIN
SELECT @synonymName = [Name]
FROM Synonyms
WHERE [ID] = @i
SELECT @sql = 'SELECT TOP (1) *
FROM [dbo].[synonym' + @synonymName + '] as syn
WHERE [syn].[Id] = tr.[Id]
ORDER BY [syn].[System.ChangedDate] DESC'
INSERT INTO @tmp
SELECT col1, col2
FROM
(
SELECT * FROM TableThatHasRelatedDataFromAllTheSynonyms
WHERE [Date] > @dateFrom
) AS tr
OUTER APPLY (EXEC(@sql)) result
SET @i = @i + 1
END
我也感谢有关如何简化解决方案的任何想法。