--DDL触发器
CREATE   TRIGGER [TR_create_drop_alter_Table]
ON DATABASE
FOR CREATE_TABLE,DROP_table,ALTER_TABLE
AS
IF(  SUSER_SNAME() <>'sa'  )
   BEGIN
   PRINT '您无Create/Alter/Drop TABLE 的权限!有需要请与管理员联系 。'
   PRINT '***********************************************************'
   PRINT '您有对 临时表(#) 进行 Create/Alter/Drop TABLE 操作的权限。'
   ROLLBACK
END

-----------------------------------------------------------------------------------------------------------------------------------------------
--IP登录限制
CREATE  TRIGGER  [Trig_ConnectLimit]
ON ALL SERVER WITH EXECUTE AS 'SA'    ---执行用户
FOR LOGON
AS
BEGIN
IF (SELECT EVENTDATA().value('(/EVENT_INSTANCE/ClientHost)[1]', 'NVARCHAR(15)'))
    NOT IN('<local machine>','192.168.1.1','192.168.1.2') --IP地址
BEGIN
    IF HOST_NAME() NOT IN('CHEN','AF')  --机器名
    BEGIN
         ROLLBACK;
    END
END
END
-----------------------------------------------------------------------------------------------------------------------------------------------

--释放TempDb占用内存
USE [tempdb]
GO
dbcc  freesystemcache('ALL')
Go
DBCC SHRINKfile(N'tempdev' ,8) --收缩到2MB
GO
------------------------------------------------------------------------------------------------------------------------------------------------

--死锁相关

USE [master]
GO
create procedure [dbo].[sp_who_lock]
as
BEGIN
declare @spid int,@bl int
DECLARE s_cur CURSOR FOR
select  0 ,blocked
from (select * from sysprocesses where  blocked>0 ) a
where not exists(select * from (select * from sysprocesses where  blocked>0 ) b
where a.blocked=spid)
union select spid,blocked from sysprocesses where  blocked>0
OPEN s_cur
FETCH NEXT FROM s_cur INTO @spid,@bl
WHILE @@FETCH_STATUS = 0
begin
if @spid =0
select '引起数据库死锁的是:
'+ CAST(@bl AS VARCHAR(10)) + '进程号,其执行的SQL语法如下'
else
select '进程号SPID:'+ CAST(@spid AS VARCHAR(10))+ '被' + '
进程号SPID:'+ CAST(@bl AS VARCHAR(10)) +'阻塞,其当前进程执行的SQL语法如下'
DBCC INPUTBUFFER (@bl )
FETCH NEXT FROM s_cur INTO @spid,@bl
end
CLOSE s_cur
DEALLOCATE s_cur
END
GO
--查看死锁
--  EXEC [dbo].[sp_who_lock]
--解除死锁
--  KILL SPID

----------------------------------------------------------------------------------------------------------------------------------------------------

--查找出什么语句读 内存很高
SELECT SS.SUM_EXECUTION_COUNT, T.TEXT,  SS.SUM_TOTAL_ELAPSED_TIME,  SS.SUM_TOTAL_WORKER_TIME, SS.SUM_TOTAL_LOGICAL_READS,  SS.SUM_TOTAL_LOGICAL_WRITES
FROM (SELECT S.PLAN_HANDLE, SUM(S.EXECUTION_COUNT)SUM_EXECUTION_COUNT, SUM(S.TOTAL_ELAPSED_TIME)SUM_TOTAL_ELAPSED_TIME,  SUM(S.TOTAL_WORKER_TIME)SUM_TOTAL_WORKER_TIME,
            SUM(S.TOTAL_LOGICAL_READS)SUM_TOTAL_LOGICAL_READS, SUM(S.TOTAL_LOGICAL_WRITES)SUM_TOTAL_LOGICAL_WRITES
       FROM SYS.DM_EXEC_QUERY_STATS S
       GROUP BY S.PLAN_HANDLE    ) AS SS
      CROSS APPLY SYS.dm_exec_sql_text(SS.PLAN_HANDLE)T
ORDER BY SUM_TOTAL_LOGICAL_READS DESC
--------------------------------------------------------------------------------------------------------------------------------------

--数据库占用内存情况

select  database_id, case DATABASE_id when 32767 then 'resourcedb' else DB_NAME(database_id) end AS  DbName ,COUNT(*)*8.0/1024 as 'MemorySize(MB)'

from sys.dm_os_buffer_descriptors

group by DB_NAME(database_id),database_id
--------------------------------------------------------------------------------------------------------------------------------------

--查看数据字典
SELECT     
  表名=case   when   a.colorder=1   then   d.name   else   ''   end,   
  表说明=case   when   a.colorder=1   then   isnull(f.value,'')   else   ''   end,   
  字段序号=a.colorder,   
  字段名=a.name,   
  标识=case   when   COLUMNPROPERTY(   a.id,a.name,'IsIdentity')=1   then   '√'else   ''   end,   
  主键=case   when   exists(SELECT   1   FROM   sysobjects   where   xtype='PK'   and   name   in   (   
  SELECT   name   FROM   sysindexes   WHERE   indid   in(   
  SELECT   indid   FROM   sysindexkeys   WHERE   id   =   a.id   AND   colid=a.colid   
  )))   then   '√'   else   ''   end,   
  类型=b.name,   
  占用字节数=a.length,   
  长度=COLUMNPROPERTY(a.id,a.name,'PRECISION'),   
  小数位数=isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0),   
  允许空=case   when   a.isnullable=1   then   '√'else   ''   end,   
  默认值=isnull(e.text,''),   
  字段说明=isnull(g.[value],'')   
  FROM   syscolumns   a   
  left   join   systypes   b   on   a.xtype=b.xusertype   
  inner   join   sysobjects   d   on   a.id=d.id     and   d.xtype='U'   and     d.name<>'dtproperties'   
  left   join   syscomments   e   on   a.cdefault=e.id   
  left   join   sys.extended_properties g   on   a.id=g.major_id   and   a.colid=g.minor_id          
  left   join   sys.extended_properties f   on   d.id=f.major_id   and   f.minor_id   =0   
  --where   d.name='要查询的表'         --如果只查询指定表,加上此条件   
  order   by   a.id,a.colorder
------------------------------------------------------------------------------------------------------------------------------------------------

--查询当前数据库索引情况
SELECT A.DBNAME ,A.TABELNAME ,B.name , D.RowCnt ,C.[%] ,user_seeks,user_scans,user_lookups,user_updates,last_user_seek,last_user_scan,last_user_lookup,last_user_update
FROM (SELECT DB_NAME(database_id) DBNAME ,ISNULL((OBJECT_NAME(OBJECT_ID)),OBJECT_ID) TABELNAME ,index_id ,user_seeks,user_scans,user_lookups
,user_updates,last_user_seek,last_user_scan,last_user_lookup,last_user_update FROM sys.dm_db_index_usage_stats  WHERE database_id>6  AND DB_NAME(database_id) NOT IN ('distribution') AND OBJECT_NAME(OBJECT_ID) NOT LIKE 'sys%'AND database_id=DB_ID()
) A LEFT JOIN (SELECT OBJECT_NAME(OBJECT_ID) TABELNAME ,name ,index_id FROM SYS.indexes ) B ON A.TABELNAME=B.TABELNAME AND A.index_id=B.index_id  LEFT JOIN (select  ROUND(avg_fragmentation_in_percent,2)[%],DB_NAME(database_id)DBNAME, ISNULL((OBJECT_NAME(OBJECT_ID)),OBJECT_ID) TABELNAME ,index_id
from  sys.dm_db_index_physical_stats(db_id(),null, null, null, null))C ON A.DBNAME=C.DBNAME AND A.TABELNAME=C.TABELNAME AND A.index_id=C.index_id LEFT JOIN (SELECT object_name (i.id) TableName,rows as RowCnt FROM sysindexes i  INNER JOIN sysObjects o  ON (o.id = i.id AND o.xType = 'U ')   
WHERE indid < 2 ) D  ON A.TABELNAME=D.TableName
WHERE B.name IS NOT NULL
AND  C.[%]>15  
--AND user_seeks>0
--AND last_user_seek>(GETDATE()-10)
AND B.name  IS NOT NULL
ORDER BY A.TABELNAME  ,name
--生成语句
SELECT 'ALTER INDEX ' ,B.name ,' ON ',A.TABELNAME ,' REBUILD PARTITION = ALL WITH ( PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, ONLINE = OFF, SORT_IN_TEMPDB = OFF ) '
FROM (SELECT DB_NAME(database_id) DBNAME ,ISNULL((OBJECT_NAME(OBJECT_ID)),OBJECT_ID) TABELNAME ,index_id ,user_seeks,user_scans,user_lookups
,user_updates,last_user_seek,last_user_scan,last_user_lookup,last_user_update FROM sys.dm_db_index_usage_stats  WHERE database_id>6  AND DB_NAME(database_id) NOT IN ('distribution') AND OBJECT_NAME(OBJECT_ID) NOT LIKE 'sys%'AND database_id=DB_ID()
) A LEFT JOIN (SELECT OBJECT_NAME(OBJECT_ID) TABELNAME ,name ,index_id FROM SYS.indexes ) B ON A.TABELNAME=B.TABELNAME AND A.index_id=B.index_id LEFT JOIN (select  ROUND(avg_fragmentation_in_percent,2)[%],DB_NAME(database_id)DBNAME, ISNULL((OBJECT_NAME(OBJECT_ID)),OBJECT_ID) TABELNAME ,index_id
from  sys.dm_db_index_physical_stats(db_id(),null, null, null, null))C ON A.DBNAME=C.DBNAME AND A.TABELNAME=C.TABELNAME AND A.index_id=C.index_id LEFT JOIN (SELECT object_name (i.id) TableName,rows as RowCnt FROM sysindexes i  INNER JOIN sysObjects o  ON (o.id = i.id AND o.xType = 'U ')   
WHERE indid < 2 ) D  ON A.TABELNAME=D.TableName
WHERE C.[%]>20  
AND user_seeks>user_scans
--AND user_seeks>500
AND last_user_seek>(GETDATE()-2)
AND B.name  IS NOT NULL
AND RowCnt>1000
ORDER BY  A.TABELNAME  ,name
--丢失索引  
SELECT  user_seeks * avg_total_user_cost *( avg_user_impact *0.01 ) AS [index_advantage] ,  
        dbmigs.last_user_seek ,  
        dbmid.[statement] AS [Database.Schema.Table],  
        dbmid.equality_columns ,  
        dbmid.inequality_columns ,  
        dbmid.included_columns ,  
        dbmigs.unique_compiles ,  
        dbmigs.user_seeks ,  
        dbmigs.avg_total_user_cost ,  
        dbmigs.avg_user_impact  
FROM    sys.dm_db_missing_index_group_stats AS dbmigs WITH ( NOLOCK )  
        INNER JOIN sys.dm_db_missing_index_groups AS dbmig WITH ( NOLOCK ) ON dbmigs.group_handle = dbmig.index_group_handle  
        INNER JOIN sys.dm_db_missing_index_details AS dbmid WITH ( NOLOCK ) ON dbmig.index_handle = dbmid.index_handle  
WHERE   dbmid.[database_id] = DB_ID()  
ORDER BY index_advantage DESC;

---------------------------------------------------------------------------------------------------------------------------------------------

--查看账号权限

select DB_NAME(db_id()) DBNAME,b.name as TableName,c.name as UserName  , CASE b.type WHEN'U' THEN 'Table' WHEN 'P' THEN 'SP' ELSE 'Other' END AS Type
, CASE WHEN  a.ACTION = 26 AND a.PROTECTTYPE = 205 THEN '√' ELSE '' END AS 'References'
, CASE WHEN  a.ACTION = 193 AND a.PROTECTTYPE = 205 THEN '√' ELSE '' END AS 'Select'
, CASE WHEN  a.ACTION = 195 AND a.PROTECTTYPE = 205 THEN '√' ELSE '' END AS 'Insert'
, CASE WHEN  a.ACTION = 197 AND a.PROTECTTYPE = 205 THEN '√' ELSE '' END AS 'Update'
, CASE WHEN  a.ACTION = 196 AND a.PROTECTTYPE = 205 THEN '√' ELSE '' END AS 'Delete'
, CASE WHEN  a.ACTION = 224 AND a.PROTECTTYPE = 205 THEN '√' ELSE '' END AS 'Execute'
, CASE a.PROTECTTYPE WHEN 204 THEN 'Grant_W_Grant ' WHEN 205 THEN 'Grant' WHEN 206 THEN 'Deny' ELSE 'Other'   END AS Protecttype
INTO #TEMPPRI
from sysprotects a inner join sysobjects b on a.id = b.id inner join sysusers c on a.uid = c.uid

SELECT A.*,ISNULL(B.[References],'')[References],ISNULL(C.[Select],'')[Select],ISNULL(D.[Insert],'')[Insert],ISNULL(E.[Update],'')[Update],ISNULL(F.[Delete],'')[Delete],ISNULL(G.[Execute],'')[Execute]
FROM
(SELECT DISTINCT DBNAME ,TableName ,UserName ,TYPE  FROM #TEMPPRI) A
LEFT JOIN (SELECT * FROM #TEMPPRI WHERE [References] LIKE '_%' ) B  ON A.DBNAME=B.DBNAME AND A.TableName=B.TableName AND A.UserName=B.UserName
LEFT JOIN (SELECT * FROM #TEMPPRI  WHERE [Select] LIKE '_%') C  ON A.DBNAME=C.DBNAME AND A.TableName=C.TableName AND A.UserName=C.UserName
LEFT JOIN (SELECT * FROM #TEMPPRI  WHERE [Insert]LIKE '_%') D  ON A.DBNAME=D.DBNAME AND A.TableName=D.TableName AND A.UserName=D.UserName
LEFT JOIN (SELECT * FROM #TEMPPRI  WHERE [Update] LIKE '_%') E  ON A.DBNAME=E.DBNAME AND A.TableName=E.TableName AND A.UserName=E.UserName
LEFT JOIN (SELECT * FROM #TEMPPRI  WHERE [Delete] LIKE '_%') F  ON A.DBNAME=F.DBNAME AND A.TableName=F.TableName AND A.UserName=F.UserName
LEFT JOIN (SELECT * FROM #TEMPPRI  WHERE [Execute] LIKE '_%') G  ON A.DBNAME=G.DBNAME AND A.TableName=G.TableName AND A.UserName=G.UserName

DROP TABLE #TEMPPRI
-----------------------------------------------------------------------------------------------------------------------------------------------

--数据库备份情况

select @@servername ServerName , A.database_name  as dbName ,type ,A.BackupFinishDate ,A.[BackupSize(MB)] ,A.BackupName ,B.physical_device_name  AS PhysicalDeviceName

from (
SELECT media_set_id , database_name ,backup_size/1024/1024  AS [BackupSize(MB)]  ,Backup_finish_date BackupFinishDate,type ,name  BackupName  
FROM MSDB..backupset  where backup_finish_date>(GETDATE()-1)
) AS A LEFT JOIN
( SELECT  media_set_id ,physical_device_name  FROM MSDB..backupmediafamily
) B ON A.media_set_id=B.media_set_id
----------------------------------------------------------------------------------------------------------------------------------------------

--表的使用情况
CREATE PROCEDURE [dbo].[sys_viewTableSpace]
AS
BEGIN
SET NOCOUNT ON;
CREATE TABLE [dbo].#tableinfo(
表名 [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
记录数 [int] NULL,
预留空间 [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
使用空间 [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
索引占用空间 [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
未用空间 [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
)
insert into #tableinfo(表名, 记录数, 预留空间, 使用空间, 索引占用空间, 未用空间)
exec sp_MSforeachtable "exec sp_spaceused '?'"

select * from #tableinfo
order by 记录数 desc
drop table #tableinfo
END

使用的时候直接 :exec sys_viewtablespace

-----------------------------------------------------------------------------------------------------------------------------------------------

--查看错误日志

--日志编号(0:当前使用的)
DECLARE @FileNum INT        ;SET @FileNum=0
--查询类型(1:Sql Server 日志 ; 2:代理错误日志)  
DECLARE @TYPE INT            ;SET @TYPE=1        
--日志查询起始时间  
DECLARE @StartTime DATETIME    ;SET @StartTime=GETDATE()-1.5
--日志查询结束时间
DECLARE @endTime DATETIME    ;SET @endTime=GETDATE()          
--时间排序(ASC 或 DESC)
DECLARE @ORDER    VARCHAR(10)    ;SET @ORDER='DESC'        
exec xp_readerrorlog @FileNum,@Type,NULL,NULL,@StartTime,@EndTime,@order  

--切换 SQL Server 错误日志文件 存档(执行7次会清除全部数据)
--  EXEC sp_cycle_errorlog
--  GO

Sql Server 常用操作的更多相关文章

  1. Sql Server 常用操作2

    FOR XML PATH应用 stuID学生编号,sName代表学生姓名,hobby列存学生的爱好! SELECT B.sName,LEFT(StuList,LEN(StuList)-1) as ho ...

  2. 【sql server常用操作{增删改查}】

    use DB_x   go   drop database DB_y   create database DB_y --创建数据库   on primary --指定主数据文件   (   name= ...

  3. SQL Server 常用操作XML

    --修改FunctionNo节点值,@OperateFunctionNo为参数 set @DataXml.modify('replace value of (/CrudData/FunctionNo/ ...

  4. sql server 常用的系统存储过程

      系统存储过程 说明 sp_databases 列出服务上的所有数据库 sp_helpdb 报告有关指定数据库或所有数据库的信息 sp_renamedb 更改数据库的名称 sp_tables 返回当 ...

  5. SQL SERVER常用语法记录

    用于记录SQL SERVER常用语法,以及内置函数. 以下语句包含: WITH 临时表语法 ROW_NUMBER()内置函数,我一般主要是用来分页.针对于查出来的所有数据做一个数字排序 分页的BETW ...

  6. 【转】sql server数据库操作大全——常用语句/技巧集锦/经典语句

    本文为累计整理,有点乱,凑合着看吧! ☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆ ☆ ☆ ☆ sql 宝 典 ☆ ☆ ☆ 2012年-8月 修订版 ☆ ...

  7. SQL server 常用语句

    SQL Server中常用的SQL语句   1.概述 2.查询概述 3.单表查询 4.连接查询 5.带有exists的相关子查询 6.SQL的集合操作 7.插入操作 8.删除操作 9.修改操作 10. ...

  8. sql server 常用的函数小汇

    摘录些许sqlserver 常用到的一些函数,便于日常学习使用 一.字符转换函数1.ASCII()返回字符表达式最左端字符的ASCII 码值.在ASCII()函数中,纯数字的字符串可不用‘’括起来,但 ...

  9. sql Server 常用存储过程的优化

    优化存储过程有很多种方法,下面介绍最常用的7种. 1.使用SET NOCOUNT ON选项 我们使用SELECT语句时,除了返回对应的结果集外,还会返回相应的影响行数.使用SET NOCOUNT ON ...

随机推荐

  1. UNDO

    UNDO及事物 undo表空间是Oracle独有,在oracle开启一个事物之后,oracle对数据进行修改,同时,会把修改前的数据保存到UNDO表空间的UNDO段里.undo表空间中会自动分配und ...

  2. 用EasyWebSvr搭建Axure本地访问地址-转载加完善

    1.下载之后解压到任意一个位置,可以是桌面(反正很小不占空间),如图2:: 图2 解压之后文件目录 2.将生成的原型放在EasyWebSvr根目录下的demo之中,如图3所示: 图3  原型文件放置目 ...

  3. WCF启用日志追踪

    调用使用http post调用WCF Restful服务时,WCF会自动反序列化body里的实体,如果实体反序列化不成功时,会返回一个请求错误,让去看服务器日志.需要启用日志追踪功能,才能看到具体的情 ...

  4. day--6_python常用模块

    常用模块: time和datetime shutil模块 radom string shelve模块 xml处理 configparser处理 hashlib subprocess logging模块 ...

  5. [delphi]SetWindowsHookExA函数入口处修改

    library Project2; uses SysUtils, Classes, windows, Dialogs; {$R *.res} function GetModuleHandleA(a: ...

  6. 【转】HTML转义字符大全

    ISO Latin-1字符集:  — 制表符Horizontal tab  — 换行Line feed  — 回车Carriage Return  — Space ! ! — 惊叹号Exclamati ...

  7. C# 实现一个可取消的多线程操作 示例

    private void button1_Click(object sender, EventArgs e) { //定义一个为可取消资源标志 CancellationTokenSource cts ...

  8. redis 扩展 安装 和 memcached 安装

    在Windows下为PHP5.6安装redis扩展和memcached扩展   一.php安装redis扩展   1.使用phpinfo()函数查看PHP的版本信息,这会决定扩展文件版本       ...

  9. asp.net LINQ防止SQL注入式攻击

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...

  10. springbootboot-HttpServletRequest.getInputStream() 获取post内容

    问题描述: 在php端用curl post一段json到java springboot.在java端用request.getInputStream()获取到的数据为空. 问题确认: 询问度娘后, 她告 ...