如何在存储过程中动态选择数据库?

时间:2016-07-19 08:25:32

标签: sql

Create PROC spABC 
@dbname varchar(20) 
As
Use [@dbname] /*NOT ALLOWED*/ 
BEGIN 
... 
END

1 个答案:

答案 0 :(得分:0)

我能够通过以下方式实现我的解决方案。该脚本在BEGIN ... END

中运行
DECLARE @sql NVARCHAR(max)
SET @sql = N'Use ' + @dbName +N'
    Select  DISTINCT S.name Name,
                     S.create_date DOC, 
                     S.modify_date DOM , 
                     P.rows ROWCNT, 
                     MAX(C.column_id) COLCNT, 
                     SUM(a.total_pages) * 8 AS TotalSpaceKB,
                     SUM(a.used_pages) * 8 AS UsedSpaceKB      
    From sys.tables AS S
    LEFT JOIN  sys.partitions  P 
    ON S.object_id = P.object_id 
    LEFT JOIN  sys.columns C
    ON S.object_id = C.object_id
    INNER JOIN sys.allocation_units a 
    ON p.partition_id = a.container_id
    Group BY  S.name , S.create_date , S.modify_date , P.rows '

EXEC sp_executesql @sql