2007年12月14日 星期五

取得伺服器資料庫名稱 for MSSQL

-- 這個範例使用資料庫識別碼檢查 sysdatabases 中的每個資料庫,以決定資料庫名稱。

USE master
SELECT dbid, DB_NAME(dbid) AS DB_NAME
FROM sysdatabases
ORDER BY dbid



exec sp_databases

-- 下列為 sp_databases 內容
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO


/* Procedure for 8.0 server */
create proc sp_databases
as
set nocount on
declare @name sysname
declare @SQL nvarchar(600)

/* Use temporary table to sum up database size w/o using group by */
create table #databases (
DATABASE_ID int NOT NULL,
size int NOT NULL)

declare c1 cursor for
select name from master.dbo.sysdatabases
where has_dbaccess(name) = 1 -- Only look at databases to which we have access

open c1
fetch c1 into @name

while @@fetch_status >= 0
begin
select @SQL = 'insert into #databases
select '+ convert(sysname, db_id(@name)) + ', sum(size) from '
+ QuoteName(@name) + '.dbo.sysfiles'
/* Insert row for each database */
execute (@SQL)
fetch c1 into @name
end
deallocate c1

select
DATABASE_NAME = db_name(DATABASE_ID),
DATABASE_SIZE = size*8,/* Convert from 8192 byte pages to K */
REMARKS = convert(varchar(254),null) /* Remarks are NULL */
from #databases
order by 1

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

沒有留言: