码迷,mamicode.com
首页 > 数据库 > 详细

SQL窗体函數一例

时间:2014-10-09 02:12:18      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   os   使用   ar   文件   sp   

需求:

         MSSQL,列出服務實例中全部數據庫的例如以下信息: 數據庫ID、數據庫名、創建日期、數據文件類型、數據文件大小、數據庫總大小、文件所在路徑。


寫法(後面的百分比為所花時間占比):

-- 连接子查询  (47%)
WITH cte_TotalSize AS
(
	SELECT database_id
	      ,CAST(SUM(size) AS FLOAT)/128 AS [TotalSize(MB)]
	FROM sys.master_files
	GROUP BY database_id
)
SELECT a.database_id AS [DB_ID]
      ,b.name AS [DB_Name]
      ,b.create_date
      ,CASE a.type WHEN 1 THEN 'Log' ELSE 'Data' END AS File_Type
      ,CAST(a.size AS FLOAT)/128 AS [Size(MB)]  -- Size以页(8 KB)为单位
      ,c.[TotalSize(MB)]
      ,a.physical_Name AS File_Path
FROM sys.master_files a
INNER JOIN sys.databases b ON a.database_id = b.database_id
INNER JOIN cte_TotalSize c ON a.database_id = c.database_id


-- 标量子查询  (34%)
SELECT a.database_id AS [DB_ID]
      ,b.name AS [DB_Name]
      ,b.create_date
      ,CASE a.type WHEN 1 THEN 'Log' ELSE 'Data' END AS File_Type
      ,CAST(a.size AS FLOAT)/128 AS [Size(MB)]  -- Size以页(8 KB)为单位
      ,(SELECT CAST(SUM(size) AS FLOAT)/128 FROM sys.master_files WHERE database_id = a.database_id) AS [TotalSize(MB)]
      ,a.physical_Name AS File_Path 
FROM sys.master_files a
INNER JOIN sys.databases b ON a.database_id = b.database_id


-- 窗体函数  (19%)
SELECT a.database_id AS [DB_ID]
      ,b.name AS [DB_Name]
      ,b.create_date
      ,CASE a.type WHEN 1 THEN 'Log' ELSE 'Data' END AS File_Type
      ,CAST(a.size AS FLOAT)/128 AS [Size(MB)]  -- Size以页(8 KB)为单位
      ,CAST(SUM(size) OVER(PARTITION BY a.database_id) AS FLOAT)/128 AS [TotalSize(MB)]
      ,a.physical_Name AS File_Path 
FROM sys.master_files a
INNER JOIN sys.databases b ON a.database_id = b.database_id

結果:

bubuko.com,布布扣

均得出正確結果的上面三種方法,代碼越來越少,性能卻越來越好。。

当中第三種是使用了窗体函數,相關文檔:http://msdn.microsoft.com/zh-cn/library/ms189461.aspx


SQL窗体函數一例

标签:style   blog   http   io   os   使用   ar   文件   sp   

原文地址:http://www.cnblogs.com/yxwkf/p/4012084.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!