SQL脚本:EXEC sp_Msforeachdb

时间:2015-12-12 07:58:15

标签: sql tsql sql-server-2012 database-administration

当我在SQL Server 2012中运行此SQL脚本时,出现错误:接近'?'不正确

--USE AdventureWorks2012
EXEC sp_Msforeachdb '
USE [?];
drop table #DBSizes
create table #DBSizes (
               [name] nvarchar(256),
   [rows] int,
   [reserved] varchar(18),
   [data] varchar(18),
   [index_size] varchar(18),
   [unused] varchar(18)
   )
EXEC sp_MSforeachtable "INSERT INTO #DBSizes EXEC sp_spaceused '?' "
'
select DB_NAME() AS DB_na,
       [name] AS Table_na,
       [rows] AS[Row_count],
   [reserved] AS[Reserved_size],
   [data] AS[Data_size],
   [index_size] AS[Index_size],
   [unused] AS[Unused_size],
   CONVERT (date, SYSDATETIME()) AS [Date_sql]
   --CONVERT (time(7), SYSDATETIME()) AS [Time_sql]
from #DBSizes

我运行这些SQL脚本,没关系,但它只使用一个db:AdventureWorks2012

USE AdventureWorks2012
--EXEC sp_Msforeachdb '
--USE [?];
drop table #DBSizes
create table #DBSizes (
               [name] nvarchar(256),
   [rows] int,
   [reserved] varchar(18),
   [data] varchar(18),
   [index_size] varchar(18),
   [unused] varchar(18)
   )
EXEC sp_MSforeachtable "INSERT INTO #DBSizes EXEC sp_spaceused '?' "
--'
select DB_NAME() AS DB_na,
       [name] AS Table_na,
       [rows] AS[Row_count],
   [reserved] AS[Reserved_size],
   [data] AS[Data_size],
   [index_size] AS[Index_size],
   [unused] AS[Unused_size],
   CONVERT (date, SYSDATETIME()) AS [Date_sql]
   --CONVERT (time(7), SYSDATETIME()) AS [Time_sql]
from #DBSizes

我想获取所有数据库信息,但我不能。

1 个答案:

答案 0 :(得分:0)

我有时间尝试复制这个,但我假设你需要在你所拥有的那一行上逃避你的单引号:

EXEC sp_MSforeachtable "INSERT INTO #DBSizes EXEC sp_spaceused '?' "

你不应该:

EXEC sp_MSforeachtable "INSERT INTO #DBSizes EXEC sp_spaceused ''?'' "