在你的情況下適當的語法會是這樣的。
CREATE TABLE #TempTable([DBID] INT, DBName SYSNAME)
DECLARE @ForEachCommand VARCHAR(MAX), @lcsqlcmd VARCHAR(MAX)
SET @lcsqlcmd = 'USE [?]; SELECT DB_ID() AS [DBID], DB_NAME(DB_ID()) AS DBName'
SET @ForEachCommand =
'IF DB_ID(''?'') > 4
BEGIN
insert into #TempTable
EXEC sp_executesql N''' + @lcsqlcmd + '''
end'
print @ForEachCommand
EXECUTE master.sys.sp_MSforeachdb @ForEachCommand
SELECT * FROM #TempTable
參見:http://weblogs.sqlteam.com/joew/archive/2008/08/27/60700.aspx
注:通常它不是建立一個圍繞無證程序代碼是個好主意。
不使用無證程序的代碼如下:
SELECT database_id, name AS DBName
INTO #Databases
FROM sys.databases WHERE database_id > 4
CREATE TABLE #TempTable([DBID] INT, DBName SYSNAME)
DECLARE @lcsqlcmd NVARCHAR(MAX), @Command NVARCHAR(MAX)
SET @lcsqlcmd = 'USE [?]; SELECT DB_ID() AS [DBID], DB_NAME(DB_ID()) AS DBName'
DECLARE @DBName SYSNAME
SET @DBName = (SELECT TOP 1 DBName FROM #Databases ORDER BY DBName)
WHILE NOT @DBName IS NULL
BEGIN
SET @Command = REPLACE(@lcsqlcmd, '?', @DBName)
insert into #TempTable
EXEC sp_executesql @Command
SET @DBName = (SELECT TOP 1 DBName FROM #Databases WHERE DBName > @DBName ORDER BY DBName)
END
SELECT * FROM #TempTable
DROP TABLE #Databases
如果存儲過程只存在於一個數據庫你怎麼能指望它在每個數據庫上運行?除非存儲過程本身爲「數據庫名稱」使用參數? –