首页 > 代码库 > SQL窗体函數一例
SQL窗体函數一例
需求:
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
結果:
当中第三種是使用了窗体函數,相關文檔:http://msdn.microsoft.com/zh-cn/library/ms189461.aspx
SQL窗体函數一例
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。