Du kan ikke gøre dette dynamisk (som i uden at hårdkode alle databasenavne på forhånd) uden dynamisk SQL, og du kan ikke bruge dynamisk SQL i en funktion. Du bør under ingen omstændigheder bruge sp_MSForEachDB eller, IMHO, ved at bruge INFORMATION_SCHEMA .
Skriv en lagret procedure, der returnerer resultatsættet. Hvis du absolut har brug for at forbinde outputtet med andre ting (hvorfor ikke kode det i den lagrede procedure?), så indsæt outputtet i en #temp-tabel.
Prøv dette:
CREATE PROCEDURE dbo.AllMyColumnsEverywhereForReals
AS
BEGIN
SET NOCOUNT ON;
DECLARE @sql NVARCHAR(MAX) = N'';
SELECT @sql += '
UNION ALL SELECT
[database] = N''' + d.name + ''' COLLATE SQL_Latin1_General_CP1_CI_AI,
[schema] = s.name COLLATE SQL_Latin1_General_CP1_CI_AI,
[object] = o.name COLLATE SQL_Latin1_General_CP1_CI_AI,
[column] = c.name COLLATE SQL_Latin1_General_CP1_CI_AI,
[qualified] = QUOTENAME(''' + d.name + ''')
+ ''.'' + QUOTENAME(s.name)
+ ''.'' + QUOTENAME(c.name) COLLATE SQL_Latin1_General_CP1_CI_AS,
[type] = CASE o.type WHEN ''U'' THEN ''Table'' ELSE ''View'' END
FROM ' + QUOTENAME(d.name) + '.sys.columns AS c
INNER JOIN ' + QUOTENAME(d.name) + '.sys.objects AS o
ON c.[object_id] = o.[object_id]
INNER JOIN ' + QUOTENAME(d.name) + '.sys.schemas AS s
ON o.[schema_id] = s.[schema_id]
WHERE o.type IN (''U'', ''V'')'
FROM sys.databases AS d WHERE [state] = 0 AND name NOT IN
(N'master',N'tempdb',N'msdb',N'model',N'ReportServer',N'ReportServerTempDB');
SET @sql = STUFF(@sql, 1, 13, '');
EXEC sp_executesql @sql;
END
GO
Brug:
CREATE TABLE #x
(
db SYSNAME,
sch SYSNAME,
obj SYSNAME,
col SYSNAME,
qual NVARCHAR(390),
[type] CHAR(5)
);
INSERT #x EXEC dbo.AllMyColumnsEverywhereForReals;
SELECT cols FROM #x AS x -- INNER JOIN something else ON x.whatever...