LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

SQL Server 运维常用sql语句

admin
2024年7月8日 15:7 本文热度 855

一、基础命令

查看当前数据库的版本

  1. SELECT @@VERSION;

查看服务器部分特殊信息

  1. select SERVERPROPERTY(N'edition') as Edition     --数据版本,如企业版、开发版等

  2.    ,SERVERPROPERTY(N'collation') as Collation   --数据库字符集

  3.    ,SERVERPROPERTY(N'servername') as ServerName --服务名

  4.    ,@@VERSION as Version   --数据库版本号

  5.    ,@@LANGUAGE AS Language  --数据库使用的语言,如us_english

获取数据库当前时间

  1. SELECT GETDATE() AS CurrentDateTime;

查看数据库启动的参数

  1. sp_configure

查看所有数据库用户登录信息

  1. sp_helplogins

查看数据库启动时间(最近一次)

  1. select convert(varchar(30),login_time,120) from master..sysprocesses where spid=1

查看有多少个端口

  1. SELECT * FROM sys.dm_tcp_listener_states;

查看当前的连接数

  1. SELECT COUNT(*) AS [Connection Count] FROM sys.dm_exec_connections;

查看各个磁盘分区的剩余空间

  1. Exec master.dbo.xp_fixeddrives

查看数据库的磁盘使用情况

  1. Exec sp_spaceused

查看数据库服务器各数据库日志文件的大小及利用率

  1. DBCC SQLPERF(LOGSPACE)

查看当前占用 cpu 资源最高的会话和其中执行的语句

  1. select spid,cmd,cpu,physical_io,memusage,

  2. (select top 1 [text] from ::fn_get_sql(sql_handle)) sql_text

  3. from master..sysprocesses order by cpu desc,physical_io desc

查看缓存中重用次数少,占用内存大的查询语句(当前缓存中未释放的)

  1. SELECT TOP 100 usecounts, objtype, p.size_in_bytes,[sql].[text]

  2. FROM sys.dm_exec_cached_plans p OUTER APPLY sys.dm_exec_sql_text (p.plan_handle) sql

  3. ORDER BY usecounts,p.size_in_bytes  desc

看BUFFER POOL中,都缓存了哪些表(当前数据库)的数据

  1. select OBJECT_NAME(object_id) 表名,COUNT(*) 页数,COUNT(*)*8/1024.0 Mb                              

  2. from   sys.dm_os_buffer_descriptors a,sys.allocation_units b,sys.partitions c                              

  3. where  a.allocation_unit_id=b.allocation_unit_id  

  4.       and b.container_id=c.hobt_id            

  5.       and database_id=DB_ID()                              

  6. group by OBJECT_NAME(object_id)                          

  7. order by 2 desc

查看用户的权限

  1. EXEC sp_helprotect;

查看当前数据库内存使用情况

  1. select * from sys.dm_os_process_memory

查询当前数据库缓存的所有数据页面,哪些数据表,缓存的数据页面数量

  1. -- 查询当前数据库缓存的所有数据页面,哪些数据表,缓存的数据页面数量

  2. -- 从这些信息可以看出,系统经常要访问的都是哪些表,有多大?

  3. select p.object_id, object_name=object_name(p.object_id), p.index_id, buffer_pages=count(*)

  4. from sys.allocation_units a,

  5.    sys.dm_os_buffer_descriptors b,

  6.    sys.partitions p

  7. where a.allocation_unit_id=b.allocation_unit_id

  8.    and a.container_id=p.hobt_id

  9.    and b.database_id=db_id()

  10. group by p.object_id,p.index_id

  11. order by buffer_pages desc

查询缓存中具体的执行计划,及对应的SQL

  1. -- 查询缓存中具体的执行计划,及对应的SQL

  2. -- 将此结果按照数据表或SQL进行统计,可以作为基线,调整索引时考虑

  3. -- 查询结果会很大,注意将结果集输出到表或文件中

  4. SELECT  usecounts ,

  5.        refcounts ,

  6.        size_in_bytes ,

  7.        cacheobjtype ,

  8.        objtype ,

  9.        TEXT

  10. FROM    sys.dm_exec_cached_plans cp

  11.        CROSS APPLY sys.dm_exec_sql_text(plan_handle)

  12. ORDER BY objtype DESC ;

  13. GO

查看具体某个用户的权限

SELECT p.class_desc, OBJECT_NAME(p.major_id) AS object_name, p.permission_name, p.state_desc, u.name AS user_name
FROM sys.database_permissions p
JOIN sys.database_principals u ON p.grantee_principal_id = u.principal_id
WHERE u.name = ‘test’

查看注册时的实例名

  1. SELECT * FROM sys.servers;

查询用户角色

  1. select SrvRole = g.name, MemberName = u.name, MemberSID = u.sid  

  2. from sys.server_principals u, sys.server_principals g, sys.server_role_members m  

  3. where g.principal_id = m.role_principal_id  

  4. and u.principal_id = m.member_principal_id  

  5. order by 1, 2  

  6. go

看服务器角色

  1. select 用户名 = u.name,管理员权限 = g.name,是否在用 = u.is_disabled,MemberSID = u.sid  

  2. from sys.server_principals u, sys.server_principals g, sys.server_role_members m  

  3. where g.principal_id = m.role_principal_id  

  4. and u.principal_id = m.member_principal_id  

  5. and g.name = 'sysadmin'

  6. order by 1, 2

  7. go

查询当前用户所有用户表

  1. select name from sysobjects where xtype='u' order by name

查看所有的数据库

  1. Select Name FROM Master..SysDatabases orDER BY Name

查看服务器角色相关信息

  1. SP_HELPSRVROLE

  2. SP_HELPSRVROLEMEMBER 服务器角色

  3. SP_HELPSRVROLE 服务器角色

查看数据库角色相关信息

  1. SP_HELPROLE

  2. SP_HELPROLEMEMBER 数据库角色

  3. SP_HELPROLE 数据库角色

查看用户相关信息

  1. SP_HELPUSER

  2. SP_HELPUSER 数据库用户名

查看上次启动以来尝试的连接数

  1. select @@connections //返回 SQL Server 自上次启动以来尝试的连接数,无论连接是成功还是失败

当前实例允许同时进行的最大用户连接数

  1. select @@max_connections

  2. //返回 SQL Server 实例允许同时进行的最大用户连接数。返回的数值不一定是当前配置的数值

查询当前最大的连接数

  1. SELECT value_in_use

  2. FROM sys.configurations c

  3. WHERE c.name = 'user connections'; #0表示无限制

设置修改连接数

  1. exec sp_configure 'show advanced options', 1

  2. RECONFIGURE WITH OVERRIDE

  3. exec sp_configure 'user connections', 300

  4. RECONFIGURE WITH OVERRIDE

查询当前会话超时时间

  1. select @@lock_timeout //返回当前会话的当前锁定超时设置(毫秒)。

查询每个用户的连接数

  1. select loginame,count(1) as Nums

  2. from sys.sysprocesses

  3. group by loginame

  4. order by 2 desc

  5. select spid,ecid,status,loginame,hostname,cmd,request_id

  6. from sys.sysprocesses where loginame='' and hostname=''

查看当前活动的实例

  1. SELECT CURRENT_USER AS [Current User], SESSION_USER AS [Session User];

查看当前活动进程

  1. SELECT * FROM sys.dm_exec_requests;

查看所有数据库的大小

  1. SELECT

  2.    DB_NAME(database_id) AS DatabaseName,

  3.    SUM(size/128.0) AS SizeInMB,

  4.    SUM(size/128.0)/1024 AS SizeInGB

  5. FROM

  6.    sys.master_files

  7. GROUP BY

  8.    database_id

  9. ORDER BY

  10.    SizeInMB DESC;

查看某个数据库的大小

  1. SELECT sys.databases.name AS [Database Name],

  2.    CAST(SUM(size * 8 / 1024.0) AS DECIMAL(10,2)) AS [Size (MB)]

  3. FROM sys.master_files

  4. INNER JOIN sys.databases ON sys.master_files.database_id = sys.databases.database_id

  5. WHERE sys.databases.name = 'master'

  6. GROUP BY sys.databases.name;

  7. #也可以用EXEC sp_spaceused @updateusage = N'TRUE';

查看当前数据库的日志大小

  1. SELECT sys.databases.name AS [Database Name],

  2.    CAST(size * 8 / 1024.0 AS DECIMAL(10,2)) AS [Log File Size (MB)]

  3. FROM sys.master_files

  4. INNER JOIN sys.databases ON sys.master_files.database_id = sys.databases.database_id

  5. WHERE sys.databases.name = 'master'

  6.    AND sys.master_files.type = 1;

查询当前数据库的表和视图

  1. SELECT TABLE_NAME AS [Table/View Name], TABLE_TYPE AS [Type]

  2. FROM INFORMATION_SCHEMA.TABLES

  3. WHERE TABLE_TYPE IN ('BASE TABLE', 'VIEW');

查询表结构信息

  1. sp_help 'test';

二、运维小技巧

一次性清除数据库所有表的数据(高危操作,谨慎)

  1. CREATE PROCEDURE sp_DeleteAllData  

  2. AS  

  3. EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'  

  4. EXEC sp_MSForEachTable 'ALTER TABLE ? DISABLE TRIGGER ALL'  

  5. EXEC sp_MSForEachTable 'DELETE FROM ?'  

  6. EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'  

  7. EXEC sp_MSForEachTable 'ALTER TABLE ? ENABLE TRIGGER ALL'  

  8. EXEC sp_MSFOREACHTABLE 'SELECT * FROM ?'  

  9. GO

数据备份与恢复

备份

  1. BACKUP DATABASE test TO DISK = 'C:\backup\MyDatabase.bak';

恢复

  1. RESTORE DATABASE MyDatabase FROM DISK = 'C:\backup\MyDatabase.bak';

完整数据库备份

  1. BACKUP DATABASE test

  2. TO DISK = 'C:\Backup\MyDatabase.bak'

  3. WITH FORMAT, MEDIANAME = 'MyDatabase_Full', NAME = 'Full Backup';

差异备份

  1. BACKUP DATABASE test

  2. TO DISK = 'C:\Backup\MyDatabase_diff.bak'

  3. WITH DIFFERENTIAL, FORMAT, MEDIANAME = 'MyDatabase_Diff', NAME = 'Differential Backup';

事务日志备份

  1. BACKUP LOG test

  2. TO DISK = 'C:\Backup\MyDatabase_log.trn'

  3. WITH NOFORMAT, NOINIT, NAME = N'MyDatabase_LogBackup', SKIP, NOREWIND, NOUNLOAD, STATS = 10;

还原数据库

  1. RESTORE DATABASE test

  2. FROM DISK = 'C:\Backup\MyDatabase.bak'

  3. WITH FILE = 1, NOUNLOAD, REPLACE, STATS = 5;

创建账户及数据库用户

  1. #创建账户

  2. CREATE LOGIN test WITH PASSWORD = '123123';

  3. #创建数据库用户并映射到登录名

  4. CREATE USER test FOR LOGIN test;

  5. ALTER ROLE db_datareader ADD MEMBER test; -- 给予读权限

  6. ALTER ROLE db_datawriter ADD MEMBER test; -- 给予写权限

SQL优化相关、执行时间

  1. SELECT creation_time  N'语句编译时间'  

  2.        ,last_execution_time  N'上次执行时间'  

  3.        ,total_physical_reads N'物理读取总次数'  

  4.        ,total_logical_reads/execution_count N'每次逻辑读次数'  

  5.        ,total_logical_reads  N'逻辑读取总次数'  

  6.        ,total_logical_writes N'逻辑写入总次数'  

  7.        ,execution_count  N'执行次数'  

  8.        ,total_worker_time/1000 N'所用的CPU总时间ms'  

  9.        ,total_elapsed_time/1000  N'总花费时间ms'  

  10.        ,(total_elapsed_time / execution_count)/1000  N'平均时间ms'  

  11.        ,SUBSTRING(st.text, (qs.statement_start_offset/2) + 1,  

  12.         ((CASE statement_end_offset  

  13.          WHEN -1 THEN DATALENGTH(st.text)  

  14.          ELSE qs.statement_end_offset END  

  15.            - qs.statement_start_offset)/2) + 1) N'执行语句'  

  16. FROM sys.dm_exec_query_stats AS qs  

  17. CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st  

  18. WHERE SUBSTRING(st.text, (qs.statement_start_offset/2) + 1,  

  19.         ((CASE statement_end_offset  

  20.          WHEN -1 THEN DATALENGTH(st.text)  

  21.          ELSE qs.statement_end_offset END  

  22.            - qs.statement_start_offset)/2) + 1) NOT LIKE '%fetch%'  

  23. ORDER BY  total_elapsed_time / execution_count DESC;

查看job运行持续时间

  1. SELECT

  2.     [T1].[job_id]

  3.    ,[T1].[name] AS [job_name]

  4.    ,[T2].[run_status]

  5.    ,[T2].[run_date]

  6.    ,[T2].[run_time]

  7.    ,[dbo].[agent_datetime]([T2].[run_date], [T2].[run_time]) AS [run_datetime]

  8.    ,[T2].[run_duration]

  9.    ,DATEDIFF(SECOND, '1900-01-01', DATEADD(SECOND, 31, [dbo].[agent_datetime](19000101, [run_duration]))) AS [run_duration_s]

  10. FROM

  11.    [dbo].[sysjobs] AS T1

  12.    INNER JOIN [dbo].[sysjobhistory] AS T2

  13.        ON [T2].[job_id] = [T1].[job_id]

  14. WHERE

  15.    [T1].[enabled] = 1

  16.    AND [T2].[step_id] = 0

  17.    AND [T2].[run_duration] >= 1

  18.    and [T1].[name]='PIMS_CreatePaperCraftParameterAnalysisData'

  19. ORDER BY

  20.     [T2].[job_id] ASC

  21.    ,[T2].[run_date] ASC

  22. GO

从所有缓存中释放所有未使用的缓存条目

  1. DBCC FREESYSTEMCACHE('ALL');

查询、解除死锁

  1. --查询表死锁信息

  2. select object_name(resource_associated_entity_id) as tableName, request_session_id as pid from sys.dm_tran_locks

  3. where resource_type = 'OBJECT'

  4. dbcc opentran

  5. --查看死锁的详细信息、执行的sql语句

  6. exec sp_who2 53

  7. --exec sp_who 53

  8. DBCC inputbuffer (53)

  9. --解除死锁

  10. kill 53

查询SQL Server根据CPU消耗列出前5个最差性能的查询

  1. -- Worst performing CPU bound queries

  2. SELECT TOP 5

  3.    st.text,

  4.    qp.query_plan,

  5.    qs.*

  6. FROM sys.dm_exec_query_stats qs

  7. CROSS APPLY sys.dm_exec_sql_text(qs.plan_handle) st

  8. CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp

  9. ORDER BY total_worker_time DESC

  10. GO

查询数据库中各数据表大小

  1. -- =============================================

  2. --  述:更新查询数据库中各表的大小,结果存储到数据表中

  3. -- =============================================

  4.    --查询是否存在结果存储表

  5.    IF NOT EXISTS (SELECT * FROM sysobjects where id = OBJECT_ID(N'temp_tableSpaceInfo') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)

  6.    BEGIN

  7.        --不存在则创建

  8.        CREATE TABLE temp_tableSpaceInfo

  9.        (name NVARCHAR(128),

  10.        rows char(11),

  11.        reserved VARCHAR(18),

  12.        data VARCHAR(18),

  13.        index_size VARCHAR(18),

  14.        unused VARCHAR(18))

  15.    END

  16.    --清空数据表

  17.    DELETE FROM temp_tableSpaceInfo

  18.    --定义临时变量在遍历时存储表名称

  19.    DECLARE @tablename VARCHAR(255)

  20.    --使用游标读取数据库内所有表表名

  21.    DECLARE table_list_cursor CURSOR FOR

  22.    SELECT name FROM sysobjects

  23.    WHERE OBJECTPROPERTY(id, N'IsTable') = 1 AND name NOT LIKE N'#%%' ORDER BY name

  24.    --打开游标

  25.    OPEN table_list_cursor

  26.    --读取第一条数据

  27.    FETCH NEXT FROM table_list_cursor INTO @tablename

  28.    --遍历查询到的表名

  29.    WHILE @@FETCH_STATUS = 0

  30.    BEGIN

  31.        --检查当前表是否为用户表

  32.        IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(@tablename) AND OBJECTPROPERTY(id, N'IsUserTable') = 1)

  33.        BEGIN

  34.            --当前表则读取其信息插入到表格中

  35.            EXECUTE sp_executesql N'INSERT INTO temp_tableSpaceInfo EXEC sp_spaceused @tbname', N'@tbname varchar(255)', @tbname = @tablename

  36.        END

  37.        --读取下一条数据

  38.        FETCH NEXT FROM table_list_cursor INTO @tablename

  39.    END

  40.    --释放游标

  41.    CLOSE table_list_cursor

  42.    DEALLOCATE table_list_cursor

  43.    SELECT *,replace(reserved,'KB','')/1024 数据表大小M FROM temp_tableSpaceInfo order by replace(reserved,'KB','')/1024 desc

  44.    drop table temp_tableSpaceInfo

显示如何依据I/O消耗来找出你性能最差的查询

  1. -- Worst performing I/O bound queries

  2. SELECT TOP 5

  3.    st.text,

  4.    qp.query_plan,

  5.    qs.*

  6. FROM sys.dm_exec_query_stats qs

  7. CROSS APPLY sys.dm_exec_sql_text(qs.plan_handle) st

  8. CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp

  9. ORDER BY total_logical_reads DESC

  10. GO

压缩数据库、文件、日志

  1. DBCC ShrinkFile(‘数据库名’,  targetsize);            /* 收缩数据库文件 */

  2. DBCC ShrinkFile(‘数据库名_log’,  targetsize);        /* 收缩日志文件 */

  3. Targetsize:单位为兆,必须为整数,DBCC SHRINKFILE 尝试将文件收缩到指定大小。

  4. DBCC SHRINKFILE 不会将文件收缩到小于“实际使用的空间”大小,例如“分配空间”为10M,“实际使用空间”为6M,当制定targetsize1时,则将该文件收缩到6M,不会将文件收缩到1M

  5. --收缩数据库

  6. DBCC SHRINKDATABASE(数据库名,百分比)

  7. 百分比:即“收缩后文件中的最大可用空间”,取值范围“大于等于0 小于100%”,实际使用中设为0即可。

查询数据库表字段各项属性信息,便于直接复制导出excel表

  1. SELECT  

  2.     表名       = Case When A.colorder=1 Then D.name Else '' End,  

  3.     表说明     = Case When A.colorder=1 Then isnull(F.value,'') Else '' End,  

  4.     字段序号   = A.colorder,  

  5.     字段名     = A.name,  

  6.     字段说明   = isnull(G.[value],''),  

  7.     标识       = Case When COLUMNPROPERTY( A.id,A.name,'IsIdentity')=1 Then '√'Else '' End,  

  8.     主键       = Case When exists(SELECT 1 FROM sysobjects Where xtype='PK' and parent_obj=A.id and name in (  

  9.                      SELECT name FROM sysindexes WHERE indid in( SELECT indid FROM sysindexkeys WHERE id = A.id AND colid=A.colid))) then '√' else '' end,  

  10.     类型       = B.name,  

  11.     占用字节数 = A.Length,  

  12.     长度       = COLUMNPROPERTY(A.id,A.name,'PRECISION'),  

  13.     小数位数   = isnull(COLUMNPROPERTY(A.id,A.name,'Scale'),0),  

  14.     允许空     = Case When A.isnullable=1 Then '√'Else '' End,  

  15.     默认值     = isnull(E.Text,'')  

  16. FROM  

  17.     syscolumns A  

  18. Left Join  

  19.     systypes B  

  20. On  

  21.     A.xusertype=B.xusertype  

  22. Inner Join  

  23.     sysobjects D  

  24. On  

  25.     A.id=D.id  and D.xtype='U' and  D.name<>'dtproperties'  

  26. Left Join  

  27.     syscomments E  

  28. on  

  29.     A.cdefault=E.id  

  30. Left Join  

  31. sys.extended_properties  G  

  32. on  

  33.     A.id=G.major_id and A.colid=G.minor_id  

  34. Left Join  

  35. sys.extended_properties F  

  36. On  

  37.     D.id=F.major_id and F.minor_id=0  

  38.     --where d.name='OrderInfo'    --如果只查询指定表,加上此条件  

  39. Order By  

  40.     A.id,A.colorder

数据库缓存清理

  1. CREATE PROCEDURE [dbo].ClearMemory  

  2. AS  

  3. BEGIN

  4.    --清除所有缓存

  5.    DBCC DROPCLEANBUFFERS

  6.    --打开高级配置

  7.    exec sp_configure 'show advanced options', 1

  8.    --设置最大内存值,清除现有缓存空间

  9.    exec sp_configure 'max server memory', 25600

  10.    EXEC ('RECONFIGURE')

  11.    --设置等待时间

  12.    WAITFOR DELAY '00:00:01'

  13.    --重新设置最大内存值

  14.    EXEC  sp_configure 'max server memory',40960

  15.    EXEC ('RECONFIGURE')

  16.    --关闭高级配置

  17.    exec sp_configure 'show advanced options',0

  18. END

  19. GO

三、日常运维操作

数据库用户、权限操作

  1. USE [master]

  2. GO

  3. --待确认账号密码

  4. CREATE LOGIN [NDIT] WITH PASSWORD=N'1', DEFAULT_DATABASE=[PIMS], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF

  5. GO

  6. USE PIMS

  7. go

  8. CREATE USER [NDIT] FOR LOGIN [NDIT]

  9. GO

  10. --大权限, 如果是指定的部分表,不执行这个,如果是所有内容都可以读,用此脚本

  11. --EXEC sp_addrolemember N'db_datareader', N'NDIT'

  12. --GO

  13. --指定特定表名赋予新增/更新/查询

  14. DECLARE @Sql NVARCHAR(max)

  15. SET @Sql=''

  16. --table

  17. --SELECT @Sql=@Sql+'GRANT INSERT,UPDATE,SELECT ON ['+a.name+'] TO [NDIT];' FROM sys.tables AS a WHERE name IN ('Tab1','Tab2');

  18. --view

  19. --SELECT @Sql=@Sql+'GRANT INSERT,UPDATE,SELECT ON ['+a.name+'] TO [NDIT];' FROM sys.views AS a WHERE name IN ('view1','view2');

  20. --procedure

  21. --SELECT @Sql=@Sql+'GRANT INSERT,UPDATE,SELECT ON ['+a.name+'] TO [NDIT];' FROM sys.procedures AS a WHERE name IN ('proc1','proc2');

  22. PRINT @Sql

  23. EXEC(@Sql)

  24. go

  25. --禁用登陆帐户

  26. alter login NDIT disable

  27. --启用登陆帐户

  28. alter login NDIT enable

  29. --登陆帐户改名

  30. alter login NDIT with name=dba_tom

  31. --登陆帐户改密码:

  32. alter login NDIT with password='aabb@ccdd'

  33. --数据库用户改名:

  34. alter user NDIT with name=dba_tom

  35. --更改数据库用户 defult_schema

  36. alter user NDIT with default_schema=sales

  37. --删除数据库用户:

  38. drop user NDIT

  39. --删除 SQL Server登陆帐户:

  40. drop login NDIT

查看当前用户查看当前用户

  1. select system_user

检查SQL Agent是否开启

  1. IF EXISTS (

  2. SELECT TOP 1 1

  3. FROM sys.sysprocesses

  4. WHERE program_name = 'SQLAgent - Generic Refresher'

  5. )

  6. SELECT 'Running'

  7. ELSE

  8. SELECT 'Not Running'

查看是否做了镜像

  1. select

  2.    a.database_id

  3.    ,a.name 数据库名称

  4.    ,case when b.mirroring_guid is null then '否' else '是' end 是否镜像

  5.    ,b.mirroring_partner_name 镜像服务器名称

  6. from

  7. [sys].[databases] a

  8. left join [sys].[database_mirroring] b on a.database_id=b.database_id

分离数据库

  1. USE master;

  2. EXEC sp_detach_db @dbname = 'test';#test指需要分离的数据库

附加数据库

  1. SELECT type_desc, name, physical_name from sys.database_files;#查看物理数据库文件的位置

  2. #使用带 FOR ATTACH 子句的 CREATE DATABASE 语句附加之前分离的test数据库

  3. CREATE DATABASE test  

  4.    ON (FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\DATA\test.mdf'),  

  5.    (FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\DATA\test_log.ldf')  

  6.    FOR ATTACH;

查看主从复制关系

  1. SELECT * FROM msdb.dbo.sysjobs

  2. SELECT

  3.    serverproperty('servername') AS ServerName,

  4.    CASE

  5.        WHEN serverproperty('servername') = '主服务器名称' THEN '主服务器'

  6.        ELSE '从服务器'

  7.    END AS ServerRole

  8. #也可以通过以下语句来查询

  9.    SELECT * FROM sys.objects WHERE name = 'MSreplication_options'

查看实例级别的信息

  1. select SERVERPROPERTY ('test')

查看实例级别的某个参数allow updates的配置

  1. select * from sys.configurations where name='allow updates'

查询当前数据库的所有架构范围的对象

  1. select * from sys.all_objects

查询当前数据库的所有对象

  1. select * from sys.sysobjects

在当前数据库下可以查询到所有数据库信息,包含是否on状态

  1. select * from sys.databases

查询所有数据库信息

  1. select * from sys.sysdatabases

查询当前数据库下所有正在SQL Server 实例上运行的进程的相关信息

  1. select * from sys.sysprocesses

监控日志空间

  1. DBCC SQLPERF (LOGSPACE)

查看数据库各种设置

  1. select name,State,user_access,is_read_only,recovery_model from sys.databases

查询当前数据库是否有会话

  1. select DB_NAME(dbid),* from sys.sysprocesses where dbid=db_id('test')

查询当前阻塞的所有请求

  1. SELECT session_Id,spid,ecid,DB_NAME (sp.dbid),nt_username,er.status,wait_type,

  2. [Individual Query] =SUBSTRING (qt.text,er.statement_start_offset / 2,

  3. ( CASE

  4. WHEN er.statement_end_offset = -1

  5. THEN

  6. LEN (CONVERT (NVARCHAR (MAX), qt.text)) * 2

  7. ELSE

  8. er.statement_end_offset

  9. END

  10. - er.statement_start_offset)

  11. / 2),

  12. qt.text,program_name,Hostname,nt_domain,start_time

  13. FROM sys.dm_exec_requests er

  14. INNER JOIN sys.sysprocesses sp ON er.session_id = sp.spid

  15. CROSS APPLY sys.dm_exec_sql_text (er.sql_handle) AS qt

  16. WHERE session_Id > 50 /* Ignore system spids.*/

  17. AND sp.blocked>0 AND session_Id NOT IN (@@SPID)

查看活动线程执行的sql语句,并生成批量杀掉的语句

  1. select 'KILL '+CAST(a.spid AS NVARCHAR(100)) AS KillCmd,REPLACE(hostname,' ','') as hostname ,replace(program_name,' ','') as program_name

  2. ,REPLACE(loginame, ' ', '') AS loginame, db_name(a.dbid) AS DBname,spid,blocked,waittime/1000 as waittime

  3. ,a.status,Replace(b.text,'''','''') as sqlmessage,cpu

  4. from sys.sysprocesses as a with(nolock)

  5. cross apply sys.dm_exec_sql_text(sql_handle) as b

  6. where a.status<>'sleeping' AND a.spid<>@@SPID

查看数据库的最近备份信息

  1. SELECT database_name,type,MAX(backup_finish_date) AS backup_finish_date FROM msdb.dbo.backupset GROUP BY database_name,type ORDER BY database_name,type

  2. 备注:D 表示全备份,i 表示差异备份,L 表示日志备份

查看备份进度

  1. SELECT DB_NAME(database_id) AS Exec_DB

  2. ,percent_complete

  3. ,CASE WHEN estimated_completion_time < 36000000

  4. THEN '0' ELSE '' END + RTRIM(estimated_completion_time/1000/3600)

  5. + ':' + RIGHT('0' + RTRIM((estimated_completion_time/1000)%3600/60), 2)

  6. + ':' + RIGHT('0' + RTRIM((estimated_completion_time/1000)%60), 2) AS [Time Remaining]

  7. ,b.text as tsql

  8. ,*

  9. FROM SYS.DM_EXEC_REQUESTS

  10. cross apply sys.dm_exec_sql_text(sql_handle) as b

  11. WHERE command LIKE 'Backup%' --and database_id=db_id('cardorder')

  12. --OR command LIKE 'RESTORE%'

  13. ORDER BY 2 DESC

查询always on状态是否正常

  1. select dc.database_name, d.synchronization_health_desc, d.synchronization_state_desc, d.database_state_desc from sys.dm_hadr_database_replica_states d join sys.availability_databases_cluster dc on d.group_database_id=dc.group_database_id and d.is_local=1

查看mirror镜像信息

  1. SELECT

  2. db_name(database_id),

  3. mirroring_state_desc,

  4. mirroring_role_desc,

  5. mirroring_partner_name,

  6. mirroring_partner_instance

  7. FROM sys.database_mirroring

查看每个数据库实例的数据量大小

  1. SELECT

  2. DB_NAME(db.database_id) DatabaseName,

  3. (CAST(mfrows.RowSize AS FLOAT)*8)/1024 RowSizeMB,

  4. (CAST(mflog.LogSize AS FLOAT)*8)/1024 LogSizeMB,

  5. (CAST(mfstream.StreamSize AS FLOAT)*8)/1024 StreamSizeMB,

  6. (CAST(mftext.TextIndexSize AS FLOAT)*8)/1024 TextIndexSizeMB

  7. FROM sys.databases db

  8. LEFT JOIN (SELECT database_id, SUM(size) RowSize FROM sys.master_files WHERE type = 0 GROUP BY database_id, type) mfrows ON mfrows.database_id = db.database_id

  9. LEFT JOIN (SELECT database_id, SUM(size) LogSize FROM sys.master_files WHERE type = 1 GROUP BY database_id, type) mflog ON mflog.database_id = db.database_id

  10. LEFT JOIN (SELECT database_id, SUM(size) StreamSize FROM sys.master_files WHERE type = 2 GROUP BY database_id, type) mfstream ON mfstream.database_id = db.database_id

  11. LEFT JOIN (SELECT database_id, SUM(size) TextIndexSize FROM sys.master_files WHERE type = 4 GROUP BY database_id, type) mftext ON mftext.database_id = db.database_id

查询总耗CPU最多的前3个SQL,且最近5天出现过

  1. SELECT TOP 3

  2. total_worker_time/1000 AS [总消耗CPU 时间(ms)],execution_count [运行次数],

  3. qs.total_worker_time/qs.execution_count/1000 AS [平均消耗CPU 时间(ms)],

  4. last_execution_time AS [最后一次执行时间],max_worker_time /1000 AS [最大执行时间(ms)],

  5. SUBSTRING(qt.text,qs.statement_start_offset/2+1,

  6. (CASE WHEN qs.statement_end_offset = -1

  7. THEN DATALENGTH(qt.text)

  8. ELSE qs.statement_end_offset END -qs.statement_start_offset)/2 + 1)

  9. AS [使用CPU的语法], qt.text [完整语法],

  10. qt.dbid, dbname=db_name(qt.dbid),

  11. qt.objectid,object_name(qt.objectid,qt.dbid) ObjectName

  12. FROM sys.dm_exec_query_stats qs WITH(nolock)

  13. CROSS apply sys.dm_exec_sql_text(qs.sql_handle) AS qt

  14. WHERE execution_count>1 and last_execution_time>dateadd(dd,-5,getdate())

  15. ORDER BY total_worker_time DESC

查看当前最耗资源的10个SQL及其spid

  1. SELECT TOP 10

  2. session_id,request_id,start_time AS '开始时间',status AS '状态',

  3. command AS '命令',d_sql.text AS 'sql语句', DB_NAME(database_id) AS '数据库名',

  4. blocking_session_id AS '正在阻塞其他会话的会话ID',

  5. wait_type AS '等待资源类型',wait_time AS '等待时间',wait_resource AS '等待的资源',

  6. reads AS '物理读次数',writes AS '写次数',logical_reads AS '逻辑读次数',

  7. row_count AS '返回结果行数'

  8. FROM sys.dm_exec_requests AS d_request

  9. CROSS APPLY

  10. sys.dm_exec_sql_text(d_request.sql_handle) AS d_sql

  11. WHERE session_id>50

  12. ORDER BY cpu_time DESC

  13. --前50session_id一般是系统后台进程,sys.dm_exec_requestsstatus显示为background

always on

查看集群各节点的信息,包含节点成员的名称,类型,状态,拥有的投票仲裁数

  1. SELECT * FROM  sys.dm_hadr_cluster_members;

查看集群各节点的信息,包含节点成员的名称,节点成员上的sql实例名称

  1. select * from sys.dm_hadr_instance_node_map

查看WSFC(windows server故障转移群集)的信息,包含集群名称,仲裁类型,仲裁状态

  1. SELECT * FROM SYS.dm_hadr_cluster;

查看AG名称

  1. select * from sys.dm_hadr_name_id_map

  1. 查看集群各节点的子网信息,包含节点成员的名称,子网段,子网掩码

  1. SELECT * FROM  sys.dm_hadr_cluster_networks;

查看侦听ip

  1. select * from sys.availability_group_listeners;

查看主从各节点的状态

复制

  1. select d.is_local,dc.database_name, d.synchronization_health_desc,

  2. d.synchronization_state_desc, d.database_state_desc

  3. from sys.dm_hadr_database_replica_states d

  4. join sys.availability_databases_cluster dc

  5. on d.group_database_id=dc.group_database_id;

查看辅助副本(传说中的从库)延迟多少M日志量

  1. select db_name(database_id),log_send_queue_size/1024 delay_M,*

  2. from sys.dm_hadr_database_replica_states where is_primary_replica=0;

查看DDL操作的记录

  1. select * from Sys.traces

查询返回当前配置的内存值和当前使用的值的相关信息

  1. SELECT [name], [value], [value_in_use]

  2. FROM sys.configurations

  3. WHERE [name] = 'max server memory (MB)' OR [name] = 'min server memory (MB)';

修改内存的大小

  1. sp_configure 'show advanced options', 1;

  2. RECONFIGURE;

  3. sp_configure 'max server memory (MB)', 4096; -- 设置最大内存限制为4GB

  4. RECONFIGURE;

启用对表的压缩

  1. EXEC sp_estimate_data_compression_savings 'Production', 'TransactionHistory', NULL, NULL, 'ROW';

  2. ALTER TABLE Production.TransactionHistory REBUILD PARTITION = ALL

  3. WITH (DATA_COMPRESSION = ROW);

  4. GO

启用索引压缩

  1. SELECT name, index_id

  2. FROM sys.indexes

  3. WHERE OBJECT_NAME (object_id) = N'TransactionHistory';

  4. EXEC sp_estimate_data_compression_savings

  5.    @schema_name = 'Production',

  6.    @object_name = 'TransactionHistory',

  7.    @index_id = 2,

  8.    @partition_number = NULL,

  9.    @data_compression = 'PAGE';

  10. ALTER INDEX IX_TransactionHistory_ProductID ON Production.TransactionHistory REBUILD PARTITION = ALL WITH (DATA_COMPRESSION = PAGE);

  11. GO

读取错误日志

  1. EXEC sp_readerrorlog 0, 1, 'database', 'start'

限制错误日志大小

  1. USE [master];

  2. GO

  3. EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE',

  4.    N'Software\Microsoft\MSSQLServer\MSSQLServer',

  5.    N'ErrorLogSizeInKb', REG_DWORD, 5120;

  6. GO

CHECKPOINT检查点

  1. CHECKPOINT [ checkpoint_duration ]

查询是否有死锁

  1. WITH    CTE_SID ( BSID, SID, sql_handle )        

  2.  AS ( SELECT   blocking_session_id ,

  3.                        session_id ,

  4.                        sql_handle

  5.               FROM     sys.dm_exec_requests

  6.               WHERE    blocking_session_id <> 0

  7.               UNION ALL

  8.               SELECT   A.blocking_session_id ,

  9.                        A.session_id ,

  10.                        A.sql_handle

  11.               FROM     sys.dm_exec_requests A

  12.                       JOIN CTE_SID B ON A.SESSION_ID = B.BSID

  13.             )

  14.    SELECT  C.BSID ,  C.SID , S.login_name , S.host_name , S.status ,S.cpu_time ,

  15.            S.memory_usage ,S.last_request_start_time , S.last_request_end_time ,S.logical_reads ,

  16.            S.row_count ,

  17.            q.text

  18.    FROM    CTE_SID C

  19.            JOIN sys.dm_exec_sessions S ON C.sid = s.session_id

  20.            CROSS APPLY sys.dm_exec_sql_text(C.sql_handle) Q

  21. ORDER BY sid

查看阻塞超时设置

  1. SELECT @@LOCK_TIMEOUT

查看数据库的负载

  1. SELECT substring (a.name,0,20) as [数据库名],

  2. [连接数] = (SELECT COUNT(*) FROM master..sysprocesses b WHERE a.dbid = b.dbid), [阻塞进程] = (SELECT COUNT(*)

  3. FROM master..sysprocesses b

  4. WHERE a.dbid = b.dbid AND blocked <> 0),

  5. [总内存] = ISNULL((SELECT SUM(memusage) FROM master..sysprocesses b WHERE a.dbid = b.dbid),0),

  6. [总IO] = ISNULL((SELECT SUM(physical_io) FROM master..sysprocesses b WHERE a.dbid = b.dbid),0),

  7. [总CPU] = ISNULL((SELECT SUM(cpu) FROM master..sysprocesses b

  8. WHERE a.dbid = b.dbid),0), [总等待时间] = ISNULL((SELECT SUM(waittime)

  9. FROM master..sysprocesses b

  10. WHERE a.dbid = b.dbid),0) FROM master.dbo.sysdatabases a WITH (nolock)

  11. WHERE  DatabasePropertyEx(a.name,'Status') = 'ONLINE'

  12. ORDER BY [数据库名]

整理索引碎片

  1. 第一步:查询表的索引碎片情况

  2. DBCC SHOWCONTIG WITH ALL_INDEXES

  3. 第二步:删除并重建索引

  4. 第三步:使用DROP_EXISTING子句重建索引

  5. 第四步:执行DBCC DBREINDEX

  6. 第五步:执行DBCC INDEXDEFRAG

  7. Select 'DBCC INDEXDEFRAG ('+DB_Name()+','+Object_Name(ID)+','+Cast(INDID As Varchar)+')'+Char(10)

  8. From SysIndexes

  9. Where ID Not IN (Select ID From SYSObjects Where xType='S')

查询索引

  1. SELECT CASE  WHEN t.[type] = 'U' THEN'表'

  2.             WHEN t.[type] = 'V' THEN '视图'  END AS '类型',

  3.       SCHEMA_NAME(t.schema_id) + '.' + t.[name] AS '(表/视图)名称',

  4.       i.[name] AS 索引名称,

  5.       SUBSTRING(column_names, 1, LEN(column_names) - 1) AS '列名',

  6.       CASE WHEN i.[type] = 1 THEN '聚集索引'

  7.            WHEN i.[type] = 2 THEN  '非聚集索引'

  8.            WHEN i.[type] = 3 THEN  'XML索引'

  9.           WHEN i.[type] = 4 THEN '空间索引'

  10.           WHEN i.[type] = 5 THEN '聚簇列存储索引'

  11.           WHEN i.[type] = 6 THEN '非聚集列存储索引'

  12.       WHEN i.[type] = 7 THEN'非聚集哈希索引'

  13.           END AS '索引类型',

  14.      CASE  WHEN i.is_unique = 1 THEN'唯一' ELSE '不唯一' END AS '索引是否唯一'

  15. FROM sys.objects t

  16.    INNER JOIN sys.indexes i

  17.        ON t.object_id = i.object_id

  18.    CROSS APPLY

  19. (

  20.    SELECT col.[name] + ', '

  21.    FROM sys.index_columns ic

  22.        INNER JOIN sys.columns col

  23.           ON ic.object_id = col.object_id

  24.               AND ic.column_id = col.column_id

  25.    WHERE ic.object_id = t.object_id

  26.          AND ic.index_id = i.index_id

  27.    ORDER BY col.column_id

  28.    FOR XML PATH('')

  29. ) D(column_names)

  30. WHERE t.is_ms_shipped <> 1

  31.      AND index_id > 0

  32. ORDER BY i.[name];

整理索引

  1. select 'drop index ' + index_name + ' on ' + tab_name + ';' ,a.tab_name, a.index_Type,a.index_colum FROM (

  2. SELECT CASE  WHEN t.[type] = 'U' THEN'表'

  3.             WHEN t.[type] = 'V' THEN '视图'  END AS '类型',

  4.       SCHEMA_NAME(t.schema_id) + '.' + t.[name] AS 'tab_name',

  5.       i.[name] AS index_name,

  6.       SUBSTRING(column_names, 1, LEN(column_names) - 1) AS 'index_colum',

  7.       CASE WHEN i.[type] = 1 THEN '聚集索引'

  8.            WHEN i.[type] = 2 THEN  '非聚集索引'

  9.            WHEN i.[type] = 3 THEN  'XML索引'

  10.           WHEN i.[type] = 4 THEN '空间索引'

  11.           WHEN i.[type] = 5 THEN '聚簇列存储索引'

  12.           WHEN i.[type] = 6 THEN '非聚集列存储索引'

  13.       WHEN i.[type] = 7 THEN'非聚集哈希索引'

  14.           END AS index_Type,

  15.      CASE  WHEN i.is_unique = 1 THEN'唯一' ELSE '不唯一' END AS 'index_only'

  16. FROM sys.objects t

  17.    INNER JOIN sys.indexes i

  18.        ON t.object_id = i.object_id

  19.    CROSS APPLY

  20. (

  21.    SELECT col.[name] + ', '

  22.    FROM sys.index_columns ic

  23.        INNER JOIN sys.columns col

  24.           ON ic.object_id = col.object_id

  25.               AND ic.column_id = col.column_id

  26.    WHERE ic.object_id = t.object_id

  27.          AND ic.index_id = i.index_id

  28.    ORDER BY col.column_id

  29.    FOR XML PATH('')

  30. ) D(column_names)

  31. WHERE t.is_ms_shipped <> 1

  32.      AND index_id > 0

  33. ) a

  34. where a.index_TYpe = '非聚集索引' and a.index_only = '不唯一';

  35. select 'create index ' + 'idx_' + tab_name + '_' + a.index_colum + ' on ' + tab_name + '('  + a.index_colum + ');',

  36.       a.tab_name, a.index_Type,a.index_colum FROM (

  37. SELECT CASE  WHEN t.[type] = 'U' THEN'表'

  38.             WHEN t.[type] = 'V' THEN '视图'  END AS '类型',

  39.       SCHEMA_NAME(t.schema_id) + '.' + t.[name] AS 'tab_name',

  40.       i.[name] AS index_name,

  41.       SUBSTRING(column_names, 1, LEN(column_names) - 1) AS 'index_colum',

  42.       CASE WHEN i.[type] = 1 THEN '聚集索引'

  43.            WHEN i.[type] = 2 THEN  '非聚集索引'

  44.            WHEN i.[type] = 3 THEN  'XML索引'

  45.           WHEN i.[type] = 4 THEN '空间索引'

  46.           WHEN i.[type] = 5 THEN '聚簇列存储索引'

  47.           WHEN i.[type] = 6 THEN '非聚集列存储索引'

  48.       WHEN i.[type] = 7 THEN'非聚集哈希索引'

  49.           END AS index_Type,

  50.      CASE  WHEN i.is_unique = 1 THEN'唯一' ELSE '不唯一' END AS 'index_only'

  51. FROM sys.objects t

  52.    INNER JOIN sys.indexes i

  53.        ON t.object_id = i.object_id

  54.    CROSS APPLY

  55. (

  56.    SELECT col.[name] + ', '

  57.    FROM sys.index_columns ic

  58.        INNER JOIN sys.columns col

  59.           ON ic.object_id = col.object_id

  60.               AND ic.column_id = col.column_id

  61.    WHERE ic.object_id = t.object_id

  62.          AND ic.index_id = i.index_id

  63.    ORDER BY col.column_id

  64.    FOR XML PATH('')

  65. ) D(column_names)

  66. WHERE t.is_ms_shipped <> 1

  67.      AND index_id > 0

  68. ) a

  69. where a.index_TYpe = '非聚集索引' and index_only = '不唯一'

查看哪些表占用了比较大的磁盘空间

  1. select o.name, SUM(p.reserved_page_count) as reserved_page_count,

  2.               SUM(p.used_page_count) as used_page_count,

  3.              SUM( case when(p.index_id<2) then (p.in_row_data_page_count+ p.lob_used_page_count+p.row_overflow_used_page_count) else p.lob_used_page_count+p.row_overflow_used_page_count end ) as DataPages,

  4.              SUM( case when (p.index_id<2) then row_count else 0 end ) as rowCounts

  5. from sys.dm_db_partition_stats p

  6. inner join sys.objects o on p.object_id=o.object_id group by o.name order by rowCounts desc

查看表的占用情况

  1. SELECT

  2. name '表名',

  3. convert (char(11), row_Count) as '数据条数',

  4. (reservedpages * 8) '已用空间(KB)',

  5. (pages * 8) '数据占用空间(KB)',

  6. (CASE WHEN usedpages > pages THEN (usedpages - pages) ELSE 0 END) * 8 '索引占用空间(KB)',

  7. (CASE WHEN reservedpages > usedpages THEN (reservedpages - usedpages) ELSE 0 END) * 8 '未用空间(KB)',

  8. LTRIM (STR (reservedpages * 8/1024/1024, 15, 0) + ' GB') as '已用空间(GB)'

  9. from(

  10. SELECT name,

  11. SUM (reserved_page_count) as reservedpages ,

  12. SUM (used_page_count) as usedpages ,

  13. SUM (

  14.    CASE

  15.        WHEN (index_id < 2) THEN (in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count)

  16.        ELSE lob_used_page_count + row_overflow_used_page_count

  17.    END

  18.    ) as pages,

  19. SUM (

  20.    CASE

  21.        WHEN (index_id < 2) THEN row_count

  22.        ELSE 0

  23.    END

  24.    )  as row_Count

  25. FROM sys.dm_db_partition_stats

  26. inner join sys.objects on sys.dm_db_partition_stats.object_id=sys.objects.object_id

  27. where type='U'

  28. group by sys.objects.name

  29. union

  30. SELECT sys.objects.name,

  31. sum(reserved_page_count) as reservedpages,

  32. sum(used_page_count) as usedpages,

  33. 0 as pages,

  34. 0 as row_count

  35. from sys.objects inner join sys.internal_tables on

  36. sys.objects.object_id = sys.internal_tables.parent_id

  37. inner join sys.dm_db_partition_stats on sys.dm_db_partition_stats.object_id=sys.internal_tables.object_id

  38. where sys.internal_tables.internal_type IN (202,204,211,212,213,214,215,216)

  39. group by sys.objects.name) t

  40. order by '已用空间(KB)' desc

查看物理读高的100条SQL

  1. SELECT TOP 100

  2. a.session_id,a.client_net_address,

  3. qs.total_physical_reads,qs.execution_count,

  4. qs.total_physical_reads /qs.execution_count as avg_io,

  5. qt.text, db_name(qt.dbid) as dbname, qt.objectid

  6. FROM sys.dm_exec_query_stats qs

  7.  CROSS apply sys.dm_exec_sql_text(qs.sql_handle) as qt

  8.  Left join (select a.session_id, a.sql_handle sql_handle,b.client_net_address  client_net_address

  9.             From sys. dm_exec_requests  a, sys.dm_exec_connections b

  10.             where a.session_id = b.session_id

  11.             ) a on qs.sql_handle = a. sql_handle

  12.  ORDER BY qs.total_physical_reads desc

查看逻辑读高的100条SQL

  1. SELECT TOP 100

  2. a.session_id,a.client_net_address,

  3. qs.total_logical_reads,qs.execution_count,

  4. qs.total_logical_reads /qs.execution_count as avg_io,

  5. qt.text, db_name(qt.dbid) as dbname

  6. FROM sys.dm_exec_query_stats qs

  7. cross apply sys.dm_exec_sql_text(qs.sql_handle) as qt

  8. Left join (select a.session_id, a.sql_handle sql_handle,b.client_net_address  client_net_address

  9.             From sys. dm_exec_requests  a, sys.dm_exec_connections b

  10.             where a.session_id = b.session_id

  11.             ) a on qs.sql_handle = a. sql_handle

  12. ORDER BY qs.total_logical_reads desc

查看CPU高的100条SQL

  1. SELECT TOP 20

  2.    total_worker_time/1000 AS [总消耗CPU 时间(ms)],execution_count [运行次数],

  3.    qs.total_worker_time/qs.execution_count/1000 AS [平均消耗CPU 时间(ms)],

  4.    last_execution_time AS [最后一次执行时间],max_worker_time /1000 AS [最大执行时间(ms)],

  5.    SUBSTRING(qt.text,qs.statement_start_offset/2+1,

  6.        (CASE WHEN qs.statement_end_offset = -1

  7.        THEN DATALENGTH(qt.text)

  8.        ELSE qs.statement_end_offset END -qs.statement_start_offset)/2 + 1)

  9.    AS [使用CPU的语法], qt.text [完整语法],

  10.    qt.dbid, dbname=db_name(qt.dbid),

  11.    qt.objectid,object_name(qt.objectid,qt.dbid) ObjectName

  12. FROM sys.dm_exec_query_stats qs WITH(nolock)

  13. CROSS apply sys.dm_exec_sql_text(qs.sql_handle) AS qt

  14. WHERE execution_count>1

  15. ORDER BY  total_worker_time DESC

查看内存消耗高的SQL

  1. SELECT a.session_id,a.client_net_address,SS.SUM_EXECUTION_COUNT,

  2. T.TEXT,

  3. SS.SUM_TOTAL_ELAPSED_TIME,

  4. SS.SUM_TOTAL_WORKER_TIME,

  5. SS.SUM_TOTAL_LOGICAL_READS,

  6. SS.SUM_TOTAL_LOGICAL_WRITES

  7. FROM (SELECT S.PLAN_HANDLE,

  8. SUM(S.EXECUTION_COUNT)SUM_EXECUTION_COUNT,

  9. SUM(S.TOTAL_ELAPSED_TIME)SUM_TOTAL_ELAPSED_TIME,

  10. SUM(S.TOTAL_WORKER_TIME)SUM_TOTAL_WORKER_TIME,

  11. SUM(S.TOTAL_LOGICAL_READS)SUM_TOTAL_LOGICAL_READS,

  12. SUM(S.TOTAL_LOGICAL_WRITES)SUM_TOTAL_LOGICAL_WRITES

  13. FROM SYS.DM_EXEC_QUERY_STATS S

  14. GROUP BY S.PLAN_HANDLE

  15. ) AS SS

  16. CROSS APPLY SYS.dm_exec_sql_text(SS.PLAN_HANDLE)T

  17. Left join (select a.session_id, a.plan_handle plan_handle,b.client_net_address  client_net_address

  18.             From sys. dm_exec_requests  a, sys.dm_exec_connections b

  19.             where a.session_id = b.session_id

  20.             ) a on ss.plan_handle = a. plan_handle

  21. ORDER BY SUM_TOTAL_LOGICAL_READS DESC

查找执行慢的SQL

  1. SELECT a.session_id,a.client_net_address,

  2. (total_elapsed_time / execution_count)/1000 N'平均时间ms'

  3. ,total_elapsed_time/1000 N'总花费时间ms'

  4. ,total_worker_time/1000 N'所用的CPU总时间ms'

  5. ,total_physical_reads N'物理读取总次数'

  6. ,total_logical_reads/execution_count N'每次逻辑读次数'

  7. ,total_logical_reads N'逻辑读取总次数'

  8. ,total_logical_writes N'逻辑写入总次数'

  9. ,execution_count N'执行次数'

  10. ,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'执行语句'

  11. ,st.text

  12. ,creation_time N'语句编译时间'

  13. ,last_execution_time N'上次执行时间'

  14. FROM sys.dm_exec_query_stats AS qs

  15. CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st

  16. Left join (select a.session_id, a.sql_handle sql_handle,b.client_net_address  client_net_address

  17.             From sys. dm_exec_requests  a, sys.dm_exec_connections b

  18.             where a.session_id = b.session_id

  19.             ) a on qs.sql_handle = a. sql_handle

  20. ORDER BY total_elapsed_time / execution_count DESC

查看正在执行的SQL语句

  1. SELECT   spid,

  2.         blocked,

  3.         DB_NAME(sp.dbid) AS DBName,

  4.         program_name,

  5.         waitresource,

  6.         lastwaittype,

  7.         sp.loginame,

  8.         sp.hostname,

  9.         a.[Text] AS [TextData],

  10.         SUBSTRING(A.text, sp.stmt_start / 2,

  11.         (CASE WHEN sp.stmt_end = -1 THEN DATALENGTH(A.text) ELSE sp.stmt_end

  12.         END - sp.stmt_start) / 2) AS [current_cmd]

  13. FROM     sys.sysprocesses AS sp OUTER APPLY sys.dm_exec_sql_text (sp.sql_handle) AS A

  14. WHERE    spid > 50

日志收缩注意问题

  1. select * from sys.databases

  2. log_reuse_wait_desc nothing装态,直接收缩无限制。为log_backup时,再作一次备份,然后进行收缩。

  3. SELECT role_desc, state_desc FROM sys.database_mirroring_endpoints

  4. SELECT mirroring_safety_level_desc, mirroring_witness_name, mirroring_witness_state_desc FROM sys.database_mirroring

  5. active_transaction 表示有大事务,为database_mirroring 镜像状态异常,需要resume

检查日志空间占用及不能截断原因

  1. DBCC SQLPERF(LOGSPACE)  

  2. GO

  3. SELECT name,recovery_model_desc,log_reuse_wait,log_reuse_wait_desc

  4. FROM sys.databases

  5. GO

  6. log_reuse_wait_desc REPLICATION时,多为cdc相关,use Xxx; 重新开启cdc再关闭

查询是否开启CDC

  1. SELECT   IS_CDC_ENABLED

  2.        ,CASE WHEN IS_CDC_ENABLED = 0

  3.              THEN 'CDC功能禁用'

  4.              ELSE 'CDC功能启用'END 描述

  5. FROM     SYS.DATABASES

  6. WHERE   NAME  = 'XXXX'

开启CDC和关闭CDC

  1. 对当前数据库启用CDC

  2. USE xxx

  3. GO

  4. EXECUTE sys.sp_cdc_enable_db

  5. GO

  6. 禁用CDC

  7. USE xxx

  8. GO

  9. EXECUTE sys.sp_cdc_disable_db

  10. GO

开启表的异常捕获

  1. exec sys.sp_cdc_enable_table  @source_schema='模式名称 ',

  2. @source_name='表名称',

  3. @role_name= 'CDC角色名称'


该文章在 2024/7/8 15:13:29 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2024 ClickSun All Rights Reserved