zoukankan      html  css  js  c++  java
  • sql serverDB运维实用sql大全

    运维sql server的sql总结,包含阻塞语句、等待语句、某个时间段的sql性能查询等等常用sql语句

    ##断开库的连接,记得修改库名

    USE master
    GO
    ALTER DATABASE [DBName] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
    GO
    --查看是否还有用户连接
    SELECT * FROM sys.[sysprocesses] WHERE DB_NAME([dbid])='DBName'
    GO
    ALTER DATABASE [DBName] SET MULTI_USER
    GO

    #############mssql###############

    ##查看数据库高物理io
    SELECT *,B.client_net_address FROM SYS.SYSPROCESSES A
    LEFT JOIN SYS.dm_exec_connections B
    ON A.spid=B.session_id
    WHERE SPID>100 ORDER BY physical_io DESC

    #阻塞spid号多于50的

    select * from sys.sysprocesses where blocked<>0 and spid<50;
    #阻塞查询并按等待时间排序
    select * from sys.sysprocesses where blocked<>0 order by waittime desc

    ##查看当前cpu消耗高spid
    SELECT * FROM SYS.SYSPROCESSES WHERE SPID >50 ORDER BY cpu DESC

    ##重建索引
    DBCC DBREINDEX (表名)

    ##慢sql
    SELECT TOP 10
    [session_id],
    [request_id],
    [start_time] AS '开始时间',
    [status] AS '状态',
    [command] AS '命令',
    dest.[text] AS 'sql语句',
    DB_NAME([database_id]) AS '数据库名',
    [blocking_session_id] AS '正在阻塞其他会话的会话ID',
    [wait_type] AS '等待资源类型',
    [wait_time] AS '等待时间',
    [wait_resource] AS '等待的资源',
    [reads] AS '物理读次数',
    [writes] AS '写次数',
    [logical_reads] AS '逻辑读次数',
    [row_count] AS '返回结果行数'
    FROM sys.[dm_exec_requests] AS der
    CROSS APPLY
    sys.[dm_exec_sql_text](der.[sql_handle]) AS dest
    WHERE [session_id]>50 AND DB_NAME(der.[database_id])='AIS20150329229999'
    ORDER BY [cpu_time] DESC

    ####kill sql(一般kill之前一定要找开发确认好业务,被kill了不能kill的语句)
    SELECT * FROM master.dbo.sysprocesses WHERE dbid IN
    (
    SELECT dbid FROM master.dbo.sysdatabases
    WHERE NAME='A201701FinChengLin' --指定的数据库名字
    )

    kill spid

    #根据spid获取sql语句
    select er.session_id
    ,csql.text AS CallingSQL
    from master.sys.dm_exec_requests er
    WITH (NOLOCK)
    CROSS APPLY MASTER.sys.fn_get_sql (er.sql_handle) csql
    where er.session_id =153

    #查看cpu消耗
    SELECT TOP 10
    total_worker_time/execution_count AS avg_cpu_cost, plan_handle,
    execution_count,
    (SELECT SUBSTRING(text, statement_start_offset/2 + 1,
    (CASE WHEN statement_end_offset = -1
    THEN LEN(CONVERT(nvarchar(max), text)) * 2
    ELSE statement_end_offset
    END - statement_start_offset)/2)
    FROM sys.dm_exec_sql_text(sql_handle)) AS query_text
    FROM sys.dm_exec_query_stats
    ORDER BY [avg_cpu_cost] DESC

    #根据进程号获取语句
    dbcc inputbuffer(spid)

    ##查看阻塞
    sp_who_lock


    #查看用户权限
    WITH CTE AS
    (
    SELECT u.name AS 用户名,
    g.name AS 数据库角色,
    '√' as 'flag'
    FROM sys.database_principals u
    INNER JOIN sys.database_role_members m ON u.principal_id = m.member_principal_id
    INNER JOIN sys.database_principals g ON g.principal_id = m.role_principal_id
    )
    SELECT * FROM CTE PIVOT(MAX(flag) FOR 数据库角色 IN ([public],
    [db_owner],
    [db_accessadmin],
    [db_securityadmin],
    [db_ddladmin],
    [db_backupoperator],
    [db_datareader],
    [db_datawriter],
    [db_denydatareader],
    [db_denydatawriter])) AS T

    ##查看库连接的客户端详情
    SELECT
    SPID = er.session_id
    ,STATUS = ses.STATUS
    ,ElapsedMS = er.total_elapsed_time
    ,[Login] = ses.login_name
    ,Host = ses.host_name
    ,BlkBy = er.blocking_session_id
    ,DBName = DB_Name(er.database_id)
    ,CommandType = er.command
    ,SQLStatement = st.text
    ,ObjectName = OBJECT_NAME(st.objectid)
    ,CPUTime = er.cpu_time
    ,IOReads = er.logical_reads + er.reads
    ,IOWrites = er.writes
    ,LastWaitType = er.last_wait_type
    ,StartTime = er.start_time
    ,Protocol = con.net_transport
    ,ConnectionWrites = con.num_writes
    ,ConnectionReads = con.num_reads
    ,ClientAddress = con.client_net_address
    ,Authentication = con.auth_scheme
    FROM sys.dm_exec_requests er
    OUTER APPLY sys.dm_exec_sql_text(er.sql_handle) st
    LEFT JOIN sys.dm_exec_sessions ses
    ON ses.session_id = er.session_id
    LEFT JOIN sys.dm_exec_connections con
    ON con.session_id = ses.session_id
    WHERE er.session_id > 50
    ORDER BY
    er.blocking_session_id DESC
    ,er.session_id

    ##表授权
    use AIKZY2018
    grant select on T_AR_RECEIVEBILL to bi;

    #主从库创建用户
    在辅助副本添加登录用户,让主副本上的登录用户也可以读取辅助副本数据
    步骤1:查看主库上该账号的sid [test]为库名
    SELECT * FROM [OTWB20170213098888]..sysusers
    比如:dba 0x5FF8E51322754E4196600311D384CE03

    步骤2:在副本数据库上创建对应账号,其中 sid对应的值是主库上所查到的sid的值
    CREATE LOGIN [dba] WITH PASSWORD=N'Zd@pwd2018',
    SID = 0xA23393D37FE24C49BD272901A9B7287B, DEFAULT_DATABASE=[OTWB20170213098888],
    CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF


    ####恢复挂起
    USE master

    GO
    ALTER DATABASE cl_manager_sit SET SINGLE_USER

    GO

    ALTER DATABASE cl_manager_sit SET EMERGENCY

    GO

    DBCC CHECKDB(cl_manager_sit,REPAIR_ALLOW_DATA_LOSS)

    go

    ALTER DATABASE cl_manager_sit SET ONLINE

    GO

    ALTER DATABASE cl_manager_sit SET MULTI_USER

    GO
    ##### 查看影响性能的sql具体详情
    SELECT
    SPID = er.session_id
    ,
    STATUS = ses.STATUS
    ,
    ElapsedMS = er.total_elapsed_time
    ,
    [Login] = ses.login_name
    ,
    Host = ses.host_name
    ,
    BlkBy = er.blocking_session_id
    ,
    DBName = DB_Name(er.database_id)
    ,
    CommandType = er.command
    ,
    SQLStatement = st.text
    ,
    ObjectName = OBJECT_NAME(st.objectid)
    ,
    CPUTime = er.cpu_time
    ,
    IOReads = er.logical_reads + er.reads
    ,
    IOWrites = er.writes
    ,
    LastWaitType = er.last_wait_type
    ,
    StartTime = er.start_time
    ,
    Protocol = con.net_transport
    ,
    ConnectionWrites = con.num_writes
    ,
    ConnectionReads = con.num_reads
    ,
    ClientAddress = con.client_net_address
    ,
    Authentication = con.auth_scheme
    FROM sys.dm_exec_requests er
    OUTER APPLY sys.dm_exec_sql_text(er.sql_handle) st
    LEFT JOIN sys.dm_exec_sessions ses
    ON ses.session_id = er.session_id
    LEFT JOIN sys.dm_exec_connections con
    ON con.session_id = ses.session_id
    WHERE er.session_id > 50
    ORDER BY
    er.blocking_session_id DESC
    ,er.session_id


    ###mssql查看主从延迟
    SELECT availability_mode_desc ,
    role_desc ,
    replica_server_name ,
    last_redone_time ,
    GETDATE() now ,
    DATEDIFF(ms, last_redone_time, GETDATE()) diffMS
    FROM ( ( sys.availability_groups AS ag
    JOIN sys.availability_replicas AS ar ON ag.group_id = ar.group_id
    )
    JOIN sys.dm_hadr_availability_replica_states AS ar_state ON ar.replica_id = ar_state.replica_id
    )
    JOIN sys.dm_hadr_database_replica_states dr_state ON ag.group_id = dr_state.group_id
    AND dr_state.replica_id = ar_state.replica_id;


    ###收缩数据库(收缩是收缩数据文件的,不是收缩日志文件)
    select * from sys.sysprocesses order by waittime desc

    select * from sysfiles
    dbcc shrinkdatabase('k3')

    dbcc shrinkfile(2, 0)
    dbcc shrinkfile(1, 0)
    dbcc updateusage (0)
    ####查看某时间段的sql命令
    SELECT TOP 1000 QS.creation_time, SUBSTRING(ST.text, (QS.statement_start_offset / 2) + 1,
    ((CASE QS.statement_end_offset WHEN - 1 THEN DATALENGTH(st.text) ELSE QS.statement_end_offset END - QS.statement_start_offset) / 2) + 1)
    AS statement_text, ST.text, QS.total_worker_time
    FROM sys.dm_exec_query_stats QS CROSS APPLY sys.dm_exec_sql_text(QS.sql_handle) ST
    WHERE QS.creation_time BETWEEN '2020-02-06 13:00:00' AND '2020-02-06 15:15:00' AND ST.text LIKE '%%'
    ORDER BY QS.total_worker_time desc

    ####查看某时间段的慢sql
    SELECT TOP 20
    creation_time,
        total_worker_time/1000 AS [总消耗CPU 时间(ms)],execution_count [运行次数],
        qs.total_worker_time/qs.execution_count/1000 AS [平均消耗CPU 时间(ms)],
        last_execution_time AS [最后一次执行时间],max_worker_time /1000 AS [最大执行时间(ms)],
        SUBSTRING(qt.text,qs.statement_start_offset/2+1, 
            (CASE WHEN qs.statement_end_offset = -1 
            THEN DATALENGTH(qt.text) 
            ELSE qs.statement_end_offset END -qs.statement_start_offset)/2 + 1) 
        AS [使用CPU的语法], qt.text [完整语法],
        dbname=db_name(qt.dbid),A
        object_name(qt.objectid,qt.dbid) ObjectName
    FROM sys.dm_exec_query_stats qs WITH(nolock)
    CROSS apply sys.dm_exec_sql_text(qs.sql_handle) AS qt
    WHERE creation_time BETWEEN '2020-02-06 13:00:00' AND '2020-02-06 15:15:00'
    ORDER BY  total_worker_time DESC

    ####查看某段时间的高io sql语句
    select top 50 creation_time,
    (total_logical_reads/execution_count) as avg_logical_reads,
    (total_logical_writes/execution_count) as avg_logical_writes,
    (total_physical_reads/execution_count) as avg_phys_reads,
    Execution_count,
    statement_start_offset as stmt_start_offset, statement_end_offset as stmt_end_offset,
    substring(sql_text.text, (statement_start_offset/2),
    case
    when (statement_end_offset -statement_start_offset)/2 <=0 then 64000
    else (statement_end_offset -statement_start_offset)/2 end) as exec_statement, sql_text.text,plan_text.*
    from sys.dm_exec_query_stats
    cross apply sys.dm_exec_sql_text(sql_handle) as sql_text
    cross apply sys.dm_exec_query_plan(plan_handle) as plan_text
    where creation_time BETWEEN '2020-02-06 13:00:00' AND '2020-02-06 15:15:00'
    order by avg_logical_reads
    Desc

  • 相关阅读:
    Maker DAO 与稳定币 Dai
    0x 协议治理体系,Part-2:Q&A
    Gnosis白皮书
    Digix:密码学资产中的黄金标准
    闪电网络主心骨——HTLC(哈希时间锁定)简介
    如何减少PDF文件的大小
    以太坊:创建 ERC-20 token
    Sublime Text 3 快捷键大全
    数据库学习第二季第三集:各种编程语言从数据库中获得数据方式小结
    数据库学习第二季第三集:各种编程语言从数据库中获得数据方式小结
  • 原文地址:https://www.cnblogs.com/wudongyu/p/12284101.html
Copyright © 2011-2022 走看看