轉載51GT2017-11-23 09:16評論(0)7人閱讀sql
SQL Server平常維護經常使用的一些腳本整理。
1.sql server開啓clr權限:
exec sp_configure 'clr enabled', 1
GO
RECONFIGURE
GO
ALTER DATABASE HWMESTC SET TRUSTWORTHY ON
ALTER AUTHORIZATION ON Database::HWMESTC TO sa;數據庫
2.查詢數據庫大小
Exec sp_spaceused
select name, convert(float,size) * (8192.0/1024.0)/1024. from dbo.sysfiles緩存
3.數據庫日誌壓縮
--選擇須要使用的數據庫
USE PIMS
--將數據庫模式設置爲SIMPLE
ALTER DATABASE PIMS SET RECOVERY SIMPLE
-- 將日誌文件收縮到1M
DBCC SHRINKFILE ('PIMS_log', 1)
-- 還原數據庫
ALTER DATABASE PIMS SET RECOVERY FULLide
4.查看數據庫鏈接用戶
Select * From sys.dm_exec_connectionsfetch
5.查看當前佔用 cpu 資源最高的會話和其中執行的語句(及時CPU)
select spid,cmd,cpu,physical_io,memusage,
(select top 1 [text] from ::fn_get_sql(sql_handle)) sql_text
from master..sysprocesses order by cpu desc,physical_io desc優化
6.查看緩存中重用次數少,佔用內存大的查詢語句(當前緩存中未釋放的)--全局
SELECT TOP 100 usecounts, objtype, p.size_in_bytes,[sql].[text]
FROM sys.dm_exec_cached_plans p OUTER APPLY sys.dm_exec_sql_text (p.plan_handle) sql
ORDER BY usecounts,p.size_in_bytes descspa
7.看BUFFER POOL中,都緩存了哪些表(當前數據庫)的數據
select OBJECT_NAME(object_id) 表名,COUNT() 頁數,COUNT()*8/1024.0 Mb
from sys.dm_os_buffer_descriptors a,sys.allocation_units b,sys.partitions c
where a.allocation_unit_id=b.allocation_unit_id
and b.container_id=c.hobt_id
and database_id=DB_ID()
group by OBJECT_NAME(object_id)
order by 2 desc日誌
8.查詢SQLSERVER內存使用狀況
select * from sys.dm_os_process_memoryorm
9.查詢SqlServer整體的內存使用狀況
select type,
sum(virtual_memory_reserved_kb)0.110/1024/1024 as vm_Reserved_gb,--保留的內存
sum(virtual_memory_committed_kb)0.110/1024/1024 as vm_Committed_gb,--提交的內存
sum(awe_allocated_kb)0.110/1024/1024 as awe_Allocated_gb,--開啓AWE後使用的內存
sum(shared_memory_reserved_kb)0.110/1024/1024 as sm_Reserved_gb,--共享的保留內存
sum(shared_memory_committed_kb)0.110/1024/1024 as sm_Committed_gb--共享的提交內存
from sys.dm_os_memory_clerks
group by type
order by typeserver
10.查詢當前數據庫緩存的全部數據頁面,哪些數據表,緩存的數據頁面數量
-- 查詢當前數據庫緩存的全部數據頁面,哪些數據表,緩存的數據頁面數量
-- 從這些信息能夠看出,系統常常要訪問的都是哪些表,有多大?
select p.object_id, object_name=object_name(p.object_id), p.index_id, buffer_pages=count(*)
from sys.allocation_units a,
sys.dm_os_buffer_descriptors b,
sys.partitions p
where a.allocation_unit_id=b.allocation_unit_id
and a.container_id=p.hobt_id
and b.database_id=db_id()
group by p.object_id,p.index_id
order by buffer_pages desc
11.查詢緩存的各種執行計劃,及分別佔了多少內存
-- 查詢緩存的各種執行計劃,及分別佔了多少內存
-- 能夠對比動態查詢與參數化SQL(預約義語句)的緩存量
select cacheobjtype
, objtype
, sum(cast(size_in_bytes as bigint))/1024 as size_in_kb
, count(bucketid) as cache_count
from sys.dm_exec_cached_plans
group by cacheobjtype, objtype
order by cacheobjtype, objtype
12.查詢緩存中具體的執行計劃,及對應的SQL
-- 查詢緩存中具體的執行計劃,及對應的SQL
-- 將此結果按照數據表或SQL進行統計,能夠做爲基線,調整索引時考慮
-- 查詢結果會很大,注意將結果集輸出到表或文件中
SELECT usecounts ,
refcounts ,
size_in_bytes ,
cacheobjtype ,
objtype ,
TEXT
FROM sys.dm_exec_cached_plans cp
CROSS APPLY sys.dm_exec_sql_text(plan_handle)
ORDER BY objtype DESC ;
GO
13.查詢sql server內存總體使用狀況
--查詢sql server內存總體使用狀況
SELECT object_name, cntr_value0.110/1024/1024 ,cntr_value,cntr_type,t.counter_name,t.instance_name
FROM sys.dm_os_performance_counters t
WHERE counter_name = 'Total Server Memory (KB)';
14.一次性清楚數據庫全部表的數據
CREATE PROCEDURE sp_DeleteAllData
AS
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
EXEC sp_MSForEachTable 'ALTER TABLE ? DISABLE TRIGGER ALL'
EXEC sp_MSForEachTable 'DELETE FROM ?'
EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'
EXEC sp_MSForEachTable 'ALTER TABLE ? ENABLE TRIGGER ALL'
EXEC sp_MSFOREACHTABLE 'SELECT * FROM ?'
GO
15.SQL優化相關、執行時間
SELECT creation_time N'語句編譯時間'
,last_execution_time N'上次執行時間'
,total_physical_reads N'物理讀取總次數'
,total_logical_reads/execution_count N'每次邏輯讀次數'
,total_logical_reads N'邏輯讀取總次數'
,total_logical_writes N'邏輯寫入總次數'
,execution_count N'執行次數'
,total_worker_time/1000 N'所用的CPU總時間ms'
,total_elapsed_time/1000 N'總花費時間ms'
,(total_elapsed_time / execution_count)/1000 N'平均時間ms'
,SUBSTRING(st.text, (qs.statement_start_offset/2) + 1,
((CASE statement_end_offset
WHEN -1 THEN DATALENGTH(st.text)
ELSE qs.statement_end_offset END
qs.statement_start_offset)/2) + 1) N'執行語句'
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st
WHERE SUBSTRING(st.text, (qs.statement_start_offset/2) + 1,
((CASE statement_end_offset
WHEN -1 THEN DATALENGTH(st.text)
ELSE qs.statement_end_offset END
qs.statement_start_offset)/2) + 1) NOT LIKE '%fetch%'
ORDER BY total_elapsed_time / execution_count DESC;
16.truncate外鍵表存儲過程
USE PIMS
GO
CREATE PROCEDURE [dbo].[usp_Truncate_Table]
@TableToTruncate VARCHAR(64)
AS
BEGIN
SET NOCOUNT ON
--==變量定義
DECLARE @i int
DECLARE @Debug bit
DECLARE @Recycle bit
DECLARE @Verbose bit
DECLARE @TableName varchar(80)
DECLARE @ColumnName varchar(80)
DECLARE @ReferencedTableName varchar(80)
DECLARE @ReferencedColumnName varchar(80)
DECLARE @ConstraintName varchar(250)
DECLARE @CreateStatement varchar(max)
DECLARE @DropStatement varchar(max)
DECLARE @TruncateStatement varchar(max)
DECLARE @CreateStatementTemp varchar(max)
DECLARE @DropStatementTemp varchar(max)
DECLARE @TruncateStatementTemp varchar(max)
DECLARE @Statement varchar(max)
SET @Debug = 0--(0:將執行相關語句|1:不執行語句)
SET @Recycle = 0--(0:不建立/不清除存儲表|1:將建立/清理存儲表)
set @Verbose = 1--(1:每步執行均打印消息|0:不打印消息)
SET @i = 1
SET @CreateStatement = 'ALTER TABLE [dbo].[] WITH NOCHECK ADD CONSTRAINT [] FOREIGN KEY([]) REFERENCES [dbo].[] ([])'
SET @DropStatement = 'ALTER TABLE [dbo].[] DROP CONSTRAINT []'
SET @TruncateStatement = 'TRUNCATE TABLE []'
-- 建立外鍵臨時表
IF OBJECT_ID('tempdb..#FKs') IS NOT NULL
DROP TABLE #FKs
-- 獲取外鍵
SELECT ROW_NUMBER() OVER (ORDER BY OBJECT_NAME(parent_object_id), clm1.name) as ID,
OBJECT_NAME(constraint_object_id) as ConstraintName,
OBJECT_NAME(parent_object_id) as TableName,
clm1.name as ColumnName,
OBJECT_NAME(referenced_object_id) as ReferencedTableName,
clm2.name as ReferencedColumnName
INTO #FKs
FROM sys.foreign_key_columns fk
JOIN sys.columns clm1 ON fk.parent_column_id = clm1.column_id AND fk.parent_object_id = clm1.object_id
JOIN sys.columns clm2 ON fk.referenced_column_id = clm2.column_id AND fk.referenced_object_id= clm2.object_id
--WHERE OBJECT_NAME(parent_object_id) not in ('//tables that you do not wont to be truncated')
WHERE OBJECT_NAME(referenced_object_id) = @TableToTruncate
ORDER BY OBJECT_NAME(parent_object_id)
-- 外鍵操做(刪除|重建)表
IF Not EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Internal_FK_Definition_Storage')
BEGIN
IF @Verbose = 1
PRINT '1. 正在建立表(Internal_FK_Definition_Storage)...'
CREATE TABLE [Internal_FK_Definition_Storage]
(
ID int not null identity(1,1) primary key,
FK_Name varchar(250) not null,
FK_CreationStatement varchar(max) not null,
FK_DestructionStatement varchar(max) not null,
Table_TruncationStatement varchar(max) not null
)
END
ELSE
BEGIN
IF @Recycle = 0
BEGIN
IF @Verbose = 1
PRINT '1. 正在清理表(Internal_FK_Definition_Storage)...'
TRUNCATE TABLE [Internal_FK_Definition_Storage]
END
ELSE
PRINT '1. 正在清理表(Internal_FK_Definition_Storage)...'
END
IF @Recycle = 0
BEGIN
IF @Verbose = 1
PRINT '2. 正在備份外鍵定義...'
WHILE (@i <= (SELECT MAX(ID) FROM #FKs))
BEGIN
SET @ConstraintName = (SELECT ConstraintName FROM #FKs WHERE ID = @i)
SET @TableName = (SELECT TableName FROM #FKs WHERE ID = @i)
SET @ColumnName = (SELECT ColumnName FROM #FKs WHERE ID = @i)
SET @ReferencedTableName = (SELECT ReferencedTableName FROM #FKs WHERE ID = @i)
SET @ReferencedColumnName = (SELECT ReferencedColumnName FROM #FKs WHERE ID = @i)
SET @DropStatementTemp = REPLACE(REPLACE(@DropStatement,'',@TableName),'',@ConstraintName)
SET @CreateStatementTemp = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@CreateStatement,'',@TableName),'',@ColumnName),'',@ConstraintName),'',@ReferencedTableName),'',@ReferencedColumnName)
SET @TruncateStatementTemp = REPLACE(@TruncateStatement,'',@TableName)
INSERT INTO [Internal_FK_Definition_Storage]
SELECT @ConstraintName, @CreateStatementTemp, @DropStatementTemp, @TruncateStatementTemp
SET @i = @i + 1
IF @Verbose = 1
PRINT ' > 已備份外鍵:[' + @ConstraintName + '] 所屬表: [' + @TableName + ']'
END
END
ELSE
PRINT '2. 正在備份外鍵定義...'
IF @Verbose = 1
PRINT '3. 正在刪除外鍵...'
BEGIN TRAN
BEGIN TRY
SET @i = 1
WHILE (@i <= (SELECT MAX(ID) FROM [Internal_FK_Definition_Storage]))
BEGIN
SET @ConstraintName = (SELECT FK_Name FROM [Internal_FK_Definition_Storage] WHERE ID = @i)
SET @Statement = (SELECT FK_DestructionStatement FROM [Internal_FK_Definition_Storage] WITH (NOLOCK) WHERE ID = @i)
IF @Debug = 1
PRINT @Statement
ELSE
EXEC(@Statement)
SET @i = @i + 1
IF @Verbose = 1
PRINT ' > 已刪除外鍵:[' + @ConstraintName + ']'
END
IF @Verbose = 1
PRINT '4. 正在清理數據表...'
--先清除該外鍵所在表(因爲外鍵所在表仍可能又被其餘外鍵所引用,所以須要循環遞歸處理)(注:本處理未實現)
--請不要使用下面註釋代碼
/SET @i = 1WHILE (@i <= (SELECT MAX(ID) FROM [Internal_FK_Definition_Storage]))BEGINSET @Statement = (SELECT Table_TruncationStatement FROM [Internal_FK_Definition_Storage] WHERE ID = @i)IF @Debug = 1PRINT @StatementELSEEXEC(@Statement)SET @i = @i + 1IF @Verbose = 1PRINT ' > ' + @StatementEND /IF @Debug = 1PRINT 'TRUNCATE TABLE [' + @TableToTruncate + ']'ELSEEXEC('TRUNCATE TABLE [' + @TableToTruncate + ']')IF @Verbose = 1PRINT ' > 已清理數據表[' + @TableToTruncate + ']'IF @Verbose = 1PRINT '5. 正在重建外鍵...'SET @i = 1WHILE (@i <= (SELECT MAX(ID) FROM [Internal_FK_Definition_Storage]))BEGINSET @ConstraintName = (SELECT FK_Name FROM [Internal_FK_Definition_Storage] WHERE ID = @i)SET @Statement = (SELECT FK_CreationStatement FROM [Internal_FK_Definition_Storage] WHERE ID = @i)IF @Debug = 1PRINT @StatementELSEEXEC(@Statement)SET @i = @i + 1IF @Verbose = 1PRINT ' > 已重建外鍵:[' + @ConstraintName + ']'ENDCOMMITEND TRYBEGIN CATCHROLLBACKPRINT '出錯信息:'+ERROR_MESSAGE()END CATCHIF @Verbose = 1PRINT '6. 處理完成!'END