SQL 收集
DMV/F: https://msdn.microsoft.com/en-us/library/ms188068.aspx
SELECT c.session_id , c.auth_scheme , c.node_affinity , r.scheduler_id , s.login_name , db_name(r.database_id) AS database_name , CASE s.transaction_isolation_level WHEN 0 THEN 'Unspecified' WHEN 1 THEN 'Read Uncomitted' WHEN 2 THEN 'Read Committed' WHEN 3 THEN 'Repeatable' WHEN 4 THEN 'Serializable' WHEN 5 THEN 'Snapshot' END AS transaction_isolation_level , s.status AS SessionStatus , r.status AS RequestStatus , CASE WHEN r.sql_handle IS NULL THEN c.most_recent_sql_handle ELSE r.sql_handle END AS sql_handle , r.cpu_time , r.reads , r.writes , r.logical_reads , r.total_elapsed_time FROM sys.dm_exec_connections c INNER JOIN sys.dm_exec_sessions s ON c.session_id = s.session_id LEFT JOIN sys.dm_exec_requests r ON c.session_id = r.session_id
dm_db_*:数据库和数据库对象 dm_exec_*:执行用户代码和关联的连接 dm_os_*:内存、锁定和时间安排 dm_tran_*:事务和隔离 dm_io_*:网络和磁盘的输入/输出
In this article, I will be explaining some of the DMVs which can be used frequently to understand the current behavior of SQL Server: SQL Server related [Hardware Resources] DMV Database related DMV Index related DMV Execution related DMV 1. SQL Server Related DMV This section details the DMVs associated with SQL Server system. SQL DMV is responsible to manage server level resources specific to a SQL Server instance. This section covers DMVs related to OS, Disk and Memory. a. sys.dm_os_sys_info This view returns the information about the SQL Server machine, available resources and the resource consumption. This view returns information like the following: CPU Count: Number of logical CPUs in the server Hyperthread-ratio: Ratio of logical and physical CPUs Physical_memory_in_bytes: Amount of physical memory available Virtual_memory_in_bytes: Amount of virtual memory available Bpool_commited: Committed physical memory in buffer pool OS_Priority_class: Priority class for SQL Server process Max_workers_thread: Maximum number of workers which can be created b. sys.dm_os_hosts This view returns all the hosts registered with SQL Server 2005. This view also provides the resources used by each host. Name: Name of the host registered Type: Type of hosted component [SQL Native Interface/OLE DB/MSDART] Active_tasks_count: Number active tasks host placed Active_ios_count: I/O requests from host waiting c. sys.dm_os_schedulers Sys.dm_os_schedulers view will help you identify if there is any CPU bottleneck in the SQL Server machine. The number of runnable tasks is generally a nonzero value; a nonzero value indicates that tasks have to wait for their time slice to run. If the runnable task counts show high values, then there is a symptom of CPU bottleneck. SELECT scheduler_id,current_tasks_count,runnable_tasks_count FROM sys.dm_os_schedulers WHERE scheduler_id < 255 The above query will list all the available schedulers in the SQL Server machine and the number of runnable tasks for each scheduler. d. sys.dm_io_pending_io_requests This dynamic view will return the I/O requests pending in SQL Server side. It gives you information like: Io_type: Type of pending I/O request Io_pending: Indicates whether the I/O request is pending or has been completed by Windows Scheduler_address: Scheduler on which this I/O request was issued e. sys.dm_io_virtual_file_stats This view returns I/O statistics for data and log files [MDF and LDF file]. This view is one of the commonly used views and will help you to identify I/O file level. This will return information like: Sample_ms: Number of milliseconds since the instance of SQL Server has started Num_of_reads: Number of reads issued on the file Num_of_bytes_read: Total number of bytes read on this file Io_stall_read_ms: Total time, in milliseconds, that the users waited for reads issued on the file Num_of_writes: Number of writes made on this file Num_of_bytes_written: Total number of bytes written to the file Io_stall_write_ms: Total time, in milliseconds, that users waited for writes to be completed on the file Io_stall: Total time, in milliseconds, that users waited for I/O to be completed Size_on_disk_bytes: Number of bytes used on the disk for this file f. sys.dm_os_memory_clerks This DMV will help how much memory SQL Server has allocated through AWE. SELECT SUM(awe_allocated_kb) / 1024 as [AWE allocated, Mb] FROM sys.dm_os_memory_clerks The same DMV can be used to get the memory consumption by internal components of SQL Server 2005. SELECT TOP 10 type, SUM(single_pages_kb) as [SPA Mem, Kb] FROM sys.dm_os_memory_clerks GROUP BY type ORDER BY SUM(single_pages_kb) DESC g. sys.dm_os_ring_buffers This DMV uses RING_BUFFER_RESOURCE_MONITOR and gives information from resource monitor notifications to identify memory state changes. Internally, SQL Server has a framework that monitors different memory pressures. When the memory state changes, the resource monitor task generates a notification. This notification is used internally by the components to adjust their memory usage according to the memory state. SELECT Record FROM sys.dm_os_ring_buffers WHERE ring_buffer_type = 'RING_BUFFER_RESOURCE_MONITOR' The output of the above query will be in XML format. The output will help you in detecting any low memory notification. RING_BUFFER_OOM: Ring buffer oom contains records indicating server out-of-memory conditions. SELECT record FROM sys.dm_os_ring_buffers WHERE ring_buffer_type = 'RING_BUFFER_OOM' 2. Database Related DMV This section details the DMVs associated with SQL Server Databases. These DMVs will help to identify database space usages, partition usages, session information usages, etc... a. sys.dm_db_file_space_usage This DMV provides the space usage information of TEMPDB database. b. sys.dm_db_session_space_usage This DMV provides the number of pages allocated and de-allocated by each session for the database c. sys.dm_db_partition_stats This DMV provides page and row-count information for every partition in the current database. The below query shows all counts for all partitions of all indexes and heaps in the MSDB database: USE MSDB; GO SELECT * FROM sys.dm_db_partition_stats; The following query shows all counts for all partitions of Backup set table and its indexes USE MSDB GO SELECT * FROM sys.dm_db_partition_stats WHERE object_id = OBJECT_ID('backupset'); d. sys.dm_os_performance_counters Returns the SQL Server / Database related counters maintained by the server. The below sample query uses the dm_os_performance_counters DMV to get the Log file usage for all databases in KB. SELECT instance_name ,cntr_value 'Log File(s) Used Size (KB)' FROM sys.dm_os_performance_counters WHERE counter_name = 'Log File(s) Used Size (KB)' 3. INDEX Related DMV This section details the DMVs associated with SQL Server Databases. These DMVs will help to identify database space usages, Partition usages, Session information usages, etc. a. sys.dm_db_index_usage_stats This DMV is used to get useful information about the index usage for all objects in all databases. This also shows the amount of seeks and scan for each index. SELECT object_id, index_id, user_seeks, user_scans, user_lookups FROM sys.dm_db_index_usage_stats ORDER BY object_id, index_id All indexes which have not been used so far in as database can be identified using the below Query: SELECT object_name(i.object_id), i.name, s.user_updates, s.user_seeks, s.user_scans, s.user_lookups from sys.indexes i left join sys.dm_db_index_usage_stats s on s.object_id = i.object_id and i.index_id = s.index_id and s.database_id = 5 where objectproperty(i.object_id, 'IsIndexable') = 1 and s.index_id is null or (s.user_updates > 0 and s.user_seeks = 0 and s.user_scans = 0 and s.user_lookups = 0) order by object_name(i.object_id) Replace the Database_id with the database you are looking at. 4. Execution Related DMV Execution related DMVs will provide information regarding sessions, connections, and various requests which are coming into the SQL Server. a. sys.dm_exec_sessions This DMV will give information on each session connected to SQL Server. This DMV is similar to running sp_who2 or querying Master..sysprocesses table. SELECT session_id,login_name, last_request_end_time,cpu_time FROM sys.dm_exec_sessions WHERE session_id >= 51 – All user Sessions b. sys.dm_exec_connections This DMV shows all the connection to SQL Server. The below query uses sys.dm_exec_connections DMV to get connection information. This view returns one row for each user connection (Sessionid > =51). SELECT connection_id, session_id,client_net_address, auth_scheme FROM sys.dm_exec_connections c. sys.dm_exec_requests This DMV will give details on what each connection is actually performing in SQL Server. SELECT session_id,status, command,sql_handle,database_id FROM sys.dm_exec_requests WHERE session_id >= 51 d. sys.dm_exec_sql_text This dynamic management function returns the text of a SQL statement given a SQL handle. SELECT st.text FROM sys.dm_exec_requests r CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS st WHERE r.session_id = 51
sys.dm_exec_cached_plans - Cached query plans available to SQL Server sys.dm_exec_sessions - Sessions in SQL Server sys.dm_exec_connections - Connections to SQL Server sys.dm_db_index_usage_stats - Seeks, scans, lookups per index sys.dm_io_virtual_file_stats - IO statistics for databases and log files sys.dm_tran_active_transactions - Transaction state for an instance of SQL Server sys.dm_exec_sql_text - Returns TSQL code sys.dm_exec_query_plan - Returns query plan sys.dm_os_wait_stats - Returns information what resources SQL is waiting on sys.dm_os_performance_counters - Returns performance monitor counters related to SQL Server
Execution Related sys.dm_exec_connections sys.dm_exec_sessions sys.dm_exec_requests sys.dm_exec_cached_plans sys.dm_exec_query_plans sys.dm_exec_sql_text sys.dm_exec_query_stats Index Related sys.dm_db_index_physical_stats sys.dm_db_index_usage_stats SQL Server Operating System sys.dm_os_performance_counters sys.dm_os_schedulers sys.dm_os_nodes sys.dm_os_waiting_tasks sys.dm_os_wait_stats I/O Related sys.dm_io_virtual_file_stats
SELECT [spid] = r.session_id, [database] = DB_NAME(r.database_id), r.start_time, r.[status], r.command, /* add other interesting columns here */ [obj] = QUOTENAME(OBJECT_SCHEMA_NAME(t.objectid, t.[dbid])) + '.' + QUOTENAME(OBJECT_NAME(t.objectid, t.[dbid])), t.[text] FROM sys.dm_exec_requests AS r CROSS APPLY sys.dm_exec_sql_text(r.[sql_handle]) AS t WHERE r.session_id <> @@SPID AND r.session_id > 50 /* -- optionally: AND r.session_id IN (< list of interesting spids >) */ ; SELECT [spid] = r.session_id, [database] = DB_NAME(r.database_id), r.start_time, r.[status], r.command, [obj] = QUOTENAME(OBJECT_NAME(t.resource_associated_entity_id, r.database_id)), /* add other interesting columns here */ t.request_mode, t.request_type, t.request_status FROM sys.dm_exec_requests AS r LEFT OUTER JOIN sys.dm_tran_locks AS t ON r.transaction_id = t.request_owner_id WHERE t.request_owner_type = N'TRANSACTION' AND r.session_id <> @@SPID AND r.session_id > 50 /* -- optionally: AND r.session_id IN (< list of interesting spids >) */ ;
生成随机整数 插入数据表
declare @count int; set @count=200000; while @count>0 begin insert into dbo.Test(randKey) values(cast(ceiling(rand() * 100) as int) set @count=@count-1; end
查看数据库各表使用大小
IF NOT EXISTS ( SELECT * FROM sys.tables WHERE name = 'tablespaceinfo' ) BEGIN CREATE TABLE tablespaceinfo --创建结果存储表 ( Table_Name VARCHAR(50) , Rows_Count INT , reserved INT , datainfo INT , index_size INT , unused INT ) END DELETE FROM tablespaceinfo --清空数据表 CREATE TABLE #temp --创建结果存储表 ( nameinfo VARCHAR(50) , rowsinfo INT , reserved VARCHAR(20) , datainfo VARCHAR(20) , index_size VARCHAR(20) , unused VARCHAR(20) ) DECLARE @tablename VARCHAR(255) --表名称 DECLARE @cmdsql NVARCHAR(500) DECLARE Info_cursor CURSOR FOR SELECT '[' + TABLE_SCHEMA + '].[' + TABLE_NAME + ']' AS Table_Name FROM [INFORMATION_SCHEMA].[TABLES] WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME <> 'tablespaceinfo' OPEN Info_cursor FETCH NEXT FROM Info_cursor INTO @tablename WHILE @@FETCH_STATUS = 0 BEGIN SET @cmdsql = 'insert into #temp exec sp_spaceused ''' + @tablename + '''' EXECUTE sp_executesql @cmdsql FETCH NEXT FROM Info_cursor INTO @tablename END CLOSE Info_cursor DEALLOCATE Info_cursor GO --itlearner注:显示数据库信息 --sp_spaceused @updateusage = 'TRUE' --itlearner注:显示表信息 UPDATE #temp SET reserved = REPLACE(reserved, 'KB', '') , datainfo = REPLACE(datainfo, 'KB', '') , index_size = REPLACE(index_size, 'KB', '') , unused = REPLACE(unused, 'KB', '') INSERT INTO dbo.tablespaceinfo SELECT nameinfo , CAST(rowsinfo AS INT) , CAST(reserved AS INT) , CAST(datainfo AS INT) , CAST(index_size AS INT) , CAST(unused AS INT) FROM #temp DROP TABLE #temp SELECT Table_Name , Rows_Count , CASE WHEN reserved > 1024 THEN CAST(reserved / 1024 AS VARCHAR(10)) + 'Mb' ELSE CAST(reserved AS VARCHAR(10)) + 'KB' END AS Data_And_Index_Reserved , CASE WHEN datainfo > 1024 THEN CAST(datainfo / 1024 AS VARCHAR(10)) + 'Mb' ELSE CAST(datainfo AS VARCHAR(10)) + 'KB' END AS Used , CASE WHEN Index_size > 1024 THEN CAST(index_size / 1024 AS VARCHAR(10)) + 'Mb' ELSE CAST(index_size AS VARCHAR(10)) + 'KB' END AS index_size , CASE WHEN unused > 1024 THEN CAST(unused / 1024 AS VARCHAR(10)) + 'Mb' ELSE CAST(unused AS VARCHAR(10)) + 'KB' END AS unused FROM dbo.tablespaceinfo ORDER BY reserved DESC
查看性能方面的
1 select * from Sys.dm_exec_requests 2 select * from Sys.dm_exec_sessions 3 select * from Sys.dm_exec_connections 4 select * from sys.dm_os_wait_stats 5 select * from Sys.sysprocesses 6 7 /*检测CPU压力的另一个方法是计算可运行状态下的工作进程数量*/ 8 SELECT COUNT(*) AS workers_waiting_for_cpu, t2.Scheduler_id 9 FROM sys.dm_os_workers AS t1, sys.dm_os_schedulers AS t2 10 WHERE t1.state = 'RUNNABLE' AND t1.scheduler_address=t2.scheduler_address 11 AND t2.scheduler_id < 255 12 GROUP BY t2.scheduler_id 13 14 15 /*下面查询是找出每次执行占用CPU最多的前100位查询:*/ 16 SELECT TOP 100 total_worker_time/execution_count AS avg_cpu_cost, plan_handle, execution_count, 17 (SELECT SUBSTRING(text, statement_start_offset/2+1, 18 (CASE WHEN statement_end_offset = -1 THEN LEN(CONVERT(nvarchar(max), text)) * 2 19 ELSE statement_end_offset END - statement_end_offset)/2) 20 FROM sys.dm_exec_sql_text(sql_handle)) AS query_text 21 FROM sys.dm_exec_query_stats 22 ORDER BY avg_cpu_cost DESC 23 24 /*稍做修改,找出运行最频繁的查询:*/ 25 SELECT TOP 100 total_worker_time/execution_count AS avg_cpu_cost, plan_handle, execution_count, 26 (SELECT SUBSTRING(text,statement_start_offset/2+1, 27 (CASE WHEN statement_end_offset = -1 THEN LEN(CONVERT(nvarchar(max), text)) * 2 28 ELSE statement_end_offset END - statement_end_offset)/2) 29 FROM sys.dm_exec_sql_text(sql_handle)) AS query_text 30 FROM sys.dm_exec_query_stats 31 ORDER BY execution_count DESC 32 33 /*还可以通过下面语句得到SQLServer在优化查询计划上花费的时间:*/ 34 SELECT * FROM sys.dm_exec_query_optimizer_info 35 WHERE counter='optimizations' OR counter = 'elapsed time' 36 37 /*下面查询找到被编译得最多的前10位查询计划:*/ 38 SELECT TOP 10 plan_generation_num, execution_count, 39 (SELECT SUBSTRING(text, statement_start_offset/2+1, 40 (CASE WHEN statement_end_offset = -1 THEN LEN(CONVERT(nvarchar(max), text)) * 2 41 ELSE statement_end_offset END -statement_end_offset)/2) 42 FROM sys.dm_exec_sql_text(sql_handle)) AS query_text 43 FROM sys.dm_exec_query_stats 44 WHERE plan_generation_num> 1 45 ORDER BY plan_generation_num DESC 46 47 /*查看阻塞---blocked 指被阻塞或锁定的SPID*/ 48 select * from master .dbo.sysprocesses where blocked>0
查看执行计划相关信息
SELECT usecounts,objtype,cacheobjtype, plan_handle,query_plan,text FROM sys.dm_exec_cached_plans CROSS APPLY sys.dm_exec_query_plan(plan_handle) CROSS APPLY sys.dm_exec_sql_text(plan_handle) WHERE text LIKE '%Reference%'
--查看执行计划相关信息 select cp.usecounts as '使用次数',cp.cacheobjtype as '快取类型', objtype as '对象类型',st.text as 'TSQL',qp.query_plan as '执行计划',cp.size_in_bytes as '对象所耗用的字节' from sys.dm_exec_cached_plans cp cross apply sys.dm_exec_sql_text(plan_handle) st cross apply sys.dm_exec_query_plan(plan_handle) qp where st.text not like '%sys%'and st.text like '%B%'
执行语句平均时间/逻辑读/重用次数 情况
1 --开启 optimize for ad hoc workloads 2 sp_CONFIGURE 'show advanced options',1 3 reconfigure 4 go 5 sp_CONFIGURE 'optimize for ad hoc workloads',1 6 reconfigure 7 go 8 select * from master.sys.configurations 9 where name='optimize for ad hoc workloads' 10 go 11 12 13 select total_elapsed_time / execution_count 平均时间,total_logical_reads/execution_count 逻辑读, 14 15 usecounts 重用次数,SUBSTRING(d.text, (statement_start_offset/2) + 1, 16 17 ((CASE statement_end_offset 18 19 WHEN -1 THEN DATALENGTH(text) 20 21 ELSE statement_end_offset END 22 23 - statement_start_offset)/2) + 1) 语句执行 from sys.dm_exec_cached_plans a 24 25 cross apply sys.dm_exec_query_plan(a.plan_handle) c 26 27 ,sys.dm_exec_query_stats b 28 29 cross apply sys.dm_exec_sql_text(b.sql_handle) d 30 31 where a.plan_handle=b.plan_handle and total_logical_reads/execution_count>4000 32 33 ORDER BY total_elapsed_time / execution_count DESC;
找出前50最耗CPU的SQL语法
SELECT TOP 50 qs.total_worker_time/qs.execution_count as [Avg CPU Time], SUBSTRING(qt.text,qs.statement_start_offset/2, (case when qs.statement_end_offset = -1 then len(convert(nvarchar(max), qt.text)) * 2 else qs.statement_end_offset end -qs.statement_start_offset)/2) as query_text, qt.dbid, dbname=db_name(qt.dbid), qt.objectid FROM sys.dm_exec_query_stats qs cross apply sys.dm_exec_sql_text(qs.sql_handle) as qt ORDER BY [Avg CPU Time] DESC
查看文件组信息
SELECT df.[name], df.physical_name, df.[size], df.growth, fg.[name]
[filegroup], fg.is_default
FROM sys.database_files df
JOIN sys.filegroups fg
ON df.data_space_id = fg.data_space_id
查看索引碎片
SELECT dbInfo.name AS databaseName, objInfo.name AS objName, ixInfo.name AS ixName, index_stats.* FROM sys.dm_db_index_physical_stats(NULL,NULL,NULL,NULL,DEFAULT) AS index_stats INNER JOIN sys.databases AS dbInfo ON index_stats.database_id = dbInfo.database_id INNER JOIN sys.objects AS objInfo ON objInfo.object_id=index_stats.object_id INNER JOIN sys.indexes AS ixInfo ON index_stats.index_id = ixInfo.index_id WHERE 1=1 AND dbInfo.name=N'Pegasus' AND objInfo.name='Citation' AND ixInfo.name='IX_PID_Status'
SELECT ix.name,ix.type_desc,ixStats.page_count,ixStats.record_count,ixStats.index_level FROM sys.indexes AS ix INNER JOIN sys.dm_db_index_physical_stats(DB_ID(N'Product'),OBJECT_ID(N'dbo.Project'),NULL,NULL,'DETAILED') AS ixStats ON ix.index_id=ixStats.index_id
查看使用空间
sp_spaceused tablename
select * from sys.dm_db_index_physical_stats(DB_ID('Product'),OBJECT_ID('dbo.Project'),null,null,'sampled')
整理碎片
ALTER INDEX ALL ON Project
REBUILD
ALTER INDEX ALL ON Project
REORGANIZE
查看锁信息
SELECT request_session_id,resource_database_id, resource_type, resource_associated_entity_id,
request_status, request_mode, resource_description
FROM sys.dm_tran_locks
清除查询计划缓存
DBCC freeproccache --在生产中,注意使用
DBCC FLUSHPROCINDB(dbid) -- dbid 获取方法:select db_id('northwind')
查看缺失的索引
select * from sys.dm_db_missing_index_details select * from sys.dm_db_missing_index_groups select * from sys.dm_db_missing_index_group_stats select * from sys.dm_db_missing_index_columns(index_handle)
已知 DBCC traceon(3604,###) 的 ###
100 Display a parse tree for each command 108 Allow dynamic and host variables in create view statements 116 Print the text of the abstract query plan. Supported by Sybase, see documentation 200 Display messages about the before image of the query-tree 201 Display messages about the after image of the query tree 208 Show types of locks taken 217 Display a warning message for using the T-SQL extension of queries with grouped aggregates and columns in the select list which are not in the GROUP BY clause. 241 Compress all query-trees when ASE is started 243 Do not expand select * to column names when creating a compiled object 244 When set, the maximum length of the returned value of str_replace() is 16384, otherwise it is 255 260 Reduce TDS (Tabular Data Stream) overhead in stored procedures. Turn off done-in-behaviour packets. See also Send doneinproc tokens. 291 Changes the hierarchy and casting of datatypes to pre-11.5.1 behaviour. There was an issue is some very rare cases where a wrong result could occur, but that's been cleared up in 11.9.2 and above. 292 Never send doneinproc tokens. See also Send doneinproc tokens. 298 Display an error message when a query uses a correlated variable as an inner or outer member of an outer join. 299 Do not recompile a stored procedure that inherits a temp table from a parent procedure. 302 Print trace information on index selection, supported by Sybase, see documentation 303 Display optimizer OR strategy 304 Revert special "or" optimizer strategy to the strategy used in pre-System 11 (this traceflag resolved several bug issues in System 11, most of these bugs are fixed in ASE 11.0.3.2) 310 Show the plan as choosen by the optimizer, as well as I/O costs. Supported by Sybase see documentation 311 Display optimizers expected I/O cost 317 Show all considered plans. Supported by Sybase, see documentation 319 Display optimizer reformatting strategy 320 Turn off join order heuristics 321 Display optimizers reformatting strategy briefly 324 Turn off the like optimization for ad-hoc queries using local variables 326 Instructs the server to use arithmetic averaging when calculating density instead of a geometric weighted average when updating statistics. Useful for building better stats when an index has skew on the leading column. Use only for updating the stats of a table/index with known skewed data. 329 Turns on a strategy for fast first row return for queries using cursors with an ORDERBY. 333 Disables min-max optimization 334 Enable merge joins 353 Turn off transitive closure 362 Will disable delta project 364 Use range density instead of total density 370 Use min-max index as an alternative to the table scan for single table queries. Does not perform aggregation optimization for joins. 384 Enable JTC 396 Use min-max optimization for single table queries. 450 Sort a group by operation in the order of the groups 516 Print mapping between xchg operators and worker processes when using parallel execution. Supported by Sybase, see documentation 526 Print semi-graphical execution operator tree when showplan is enabled. Supported by Sybase, see documentation 589 Close a cursor implicitly during a cursor fetch and after an error was hit. 602 Prints out diagnostic information for deadlock prevention. 603 Prints out diagnostic information when avoiding deadlock. 615 When a read of a page does not indicate it's right identity a second read is done. When the identity is now correct the related device is suspect and ASE turns on additional diagnostic checks. The check can be turned off with the traceflag. 646 Turn off the new space allocation method as introduced in 12.5.3 for partitioned DOL tables 693 Turn off some blocking optimizations in scans such as skipping uncommitted inserts and skipping or returning uncommitted updates based on info about what columns were updated. 695 Turn off update_mode optimization completely for multi-row updates (bugfix 97199) 699 Turn off transaction logging 712 Disable procedure cache optimisation 712 Turn off engine local memory optimization. Engine local cache enhancements were added to ASE, and disabling this should not make a noticeable impact on ASE servers running with less than 5 engines. (no benchmarks). (see case 11270180) 720 disable the warning msg "memory usage in procedure headers XXX does not match memory usage count in Pss (XXXX) for server process id XXXX." This error is reported when Adaptive Server cleans up after normal completion of a batch process and determines that the memory usage tracked by the procedure header does not match the usage total maintained in the PSS. No action is required, since this is an informational message and does not result in any incorrect behavior. Upon detecting the memory count mismatch, Adaptive Server corrects the appropriate counter, completes the cleanup tasks, and continues processing. (available since ASE 12.0.0.4 ESD#1) 722 ASE (debug version) will perform additional checks on the heap memory to detect possible memory corruption. 833 Do not report Msg 880 "Your query is blocked because it tried to write and database '' is in quiesce state. Your query will proceed after the DBA performs QUIESCE DATABASE RELEASE.". 990 Allow only access to the server with the "sa" account. Supported by Sybase, see documentation 1116 Suppress Msg 1131. (The OAM page does not belong to object with index.....) 1202 Also show the blocked lock requests in master..syslocks 1204 Print deadlock information into errorlog 1205 Prints deadlock information by printing stacktraces. 1206 Disable lock promotion. 1212 Shows info about locks granted and released 1213 Used with dbcc object_stats 1217 Show info about locks being acquired 1603 Turns off async i/o and forces standard unix io. Can be useful if symptoms include transient corruption errors that may be caused by bad drives or controllers. 1605 Start secondary engines by hand 1606 Create a debug engine start file. This allows you to start up a debug engine which can access the server's shared memory for running diagnostics. 1608 Instructs server engine 0 to not on-line any other dataserver engines 1610 Boot the server with TCP_NODELAY enabled. 1611 If possible, pin shared memory -- check errorlog for success/failure. 1613 Set affinity of the ASE engine's onto particular CPUs usually pins engine 0 to processor 0, engine 1 to processor 1, etc 1615 SGI only: turn on recoverability to filesystem devices. 1625 Linux only: Revert to using cached filesystem I/O. By default, ASE on Linux opens filesystem devices using O_SYNC, unlike other Unix based releases, which means it is safe to use filesystems devices for production systems. 1630 SuSE 32 bit Linux (SuSE 9 SP1 or later), ASE incorrectly identifies AIO to be KAIO while using Posix AIO. Can lead to ASE hang. Start with this trace flag. 1642 Reserve one third of the sockets for EJB. 1649 Allow the server to run Linux Kernel Async I/O. For Linux kernel 2.6 and above, to force low level kernel async I/O. 1650 Allow copying encrypted password strings between platforms (e.g. Solaris to Linux) 2205 Show HA debugging output, supported by Sybase see documentation 2209 Used when upgrading ASE configured with high availability 2512 Instructs dbcc checkalloc to skip the syslogs table during processing. 2513 Instructs dbcc checkalloc, tablealloc and indexalloc to check for whether foreign objects are stranded on a particular segment within a database. Supported by Sybase, see documentation 2703 When using update statistics with sampling and the index/column does not have existing statistics, set join density and total density to values from the sample rather then to defaults. 3100 Load a database even when the characterset or sort order of a dump file is incompatible with the server. 3199 When ONLINE DATABASE fails with Msg 2610 (Could not find leaf row in nonclustered index partition ...) after a cross-platform database load, set the traceflag on, reload the dump and online again. 3300 Display each log record that is being processed during recovery. You may wish to redirect stdout because it can be a lot of information. 3453 During the redo pass, allow the page timestamp to fall between the log old timestamp and the log new timestamp and also for the page timestamp to be behind the log old timestamp. In such cases, fix up the page timestamp to be the log old timestamp so that the current log record will be redone. Used to compensate for bugs in the recovery of sort. This trace flag MUST only be used in exceptional cases, and only where it is known that modifying the page timestamp is the correct thing to do. If not used wisely, data corruptions can occur. (see case 11159541) 3474 Disable tuning of buffer pools on recovery 3500 Disable checkpointing. 3502 Write an entry in the errorlog when a databases is checkpointed 3504 For internal testing. Will raise a bogus log-out-of-space condition from checkpoint() 3601 Write a stacktrace to the errorlog every time an error is raised. 3604 Send trace output to the session of the client. Supported by Sybase see documentation 3605 Send trace output to the errorlog of the server. Supported by Sybase see documentation 3607 Do not start recovery when booting ASE. 3608 Recover only the master database. Do not clear tempdb or start up checkpoint process. 3609 Recover all databases. Do not clear tempdb or start up checkpoint process. 3610 Pre-System 10 behaviour: divide by zero to result in NULL instead of error 3620 Do not kill infected processes. 3635 Print diagnostic information (see case 11257124, to get info for LDAP login problem). Trace Flag 3635 Diagnostics are written to the console that started ASE. There are not written to the errorlog, even if 3605 is turned on. 3706 Performance improvement of drop table in tempdb. 3708 By default ASE (12.5.3 onwards) will release the system catalog locks during the drop of user tables in tempdb when not in DDL-IN-TRAN mode after the commit of the transaction but before post commit work started. Turns off the default behaviour 3710 Improve the performance of DROP INDEX and CREATE INDEX by releasing the system catalog locks when not in DDL-IN-TRAN mode after the commit of the transaction but before post commit work started. 4001 Display a message in the errorlog when a loginrecord is recieved 4012 Don't spawn chkptproc. 4013 Write a message to the errorlog when a login takes place. 4020 Boot without recover. 4044 Allows to log into ASE when the "sa" login is locked 4063 used by 12.0 server to turn on sqldbgr RPCs 4066 Turn off the check for invalid data being sent from a connecting client. (see case 11239779: After ugraded to ASE 1253 to 1251, getting errors when logging into application: The packet size (0) specified at login time is illegal. Legal values are between 512 and 512.) 4072 Disable the global login trigger 4073 Export the result of certain "set" command within a login trigger to the session. 4080 When an UPDATE using tsequal() is done within a stored procedure, tsequal() no longer returns a timestamp value unless the trace flag is set. 4404 to disable pushdown of Union views. Change the order of the union view and the other view in the from clause, so that the union view is the last entry in the from clause 4413 Trace queries in a 12.5 server that are join-order dependent. 4419 In some cases, outer join on view or derived table with CASE expression may perform slower due to view materialization.The workaround is to use traceflag 4419. 5303 Select into a temporary table will be executed without the table being sliced 5304 Disable the large I/O and large allocation changes done under 279883-1. 5101 Forces all I/O requests to go through engine 0. This removes the contention between processors but could create a bottleneck if engine 0 becomes busy with non-I/O tasks. 5102 Prevents engine 0 from running any non-affinitied tasks. 7103 Disable table lock promotion for text columns. 7408 Force the server to scan *log segment* allocation pages; to recalculate free log space rather than use saved counts at boot time. (see case 11195087) 7409 Force the server to scan *data* segment allocation pages; to recalculate free data page space rather than use saved counts at boot time. (see case 11195087) 7703 When assinging a value from a table into a local variable, go through the whole resultset rather than jump to last row and assing the value once. 7709 In 12.5.2, an insert inside a stored proc writes trailing white space when selecting from a char not null field. This can lead to strange results when when selecting data. The traceflag disables this padding. 7717 Disable check of client compatibility in ASE 15. See Version 15 client compatibility 7738 Support plan sharing of cached statements across different users. 7815 logs address connection requests and host / name lookups. 7824 Disable the master/query syntax in the interfaces file 7841 Make ASE IPv6 aware 7844 Enable/disable concurrent Kerberos authentication 8003 prints info on RPC calls 8203 Display statement and transaction locks on a deadlock error. 8399 Instructs the dbcc monitor command to insert a valid description into the field_name column in the sysmonitors table. Not intended for use by users. Appears in the errorlog when sp_sysmon is used. 9217 When set, RepAgent will not stop after reporting error 9289 due to an inconsistent log record found. Instead it will attempt to continue after reporting error 9290 in the error log. Supported by Sybase, see documentation 9531 Dump expensive buffer allocation analysis 10303 Invoke set completion of object ownership methodology and object resolution from old procedural ownership 11201 Logs client connect events, disconnect events, and attention events. Supported by Sybase, see documentation 11202 Logs client language, cursor declare, dynamic prepare, and dynamic execute-immediate text. Supported by Sybase, see documentation 11203 Logs client rpc events. Supported by Sybase, see documentation 11204 Logs all messages routed to client. Supported by Sybase, see documentation 11205 Logs all interaction with remote server. Supported by Sybase, see documentation 11206 Show messages about query processing for file access. Supported by Sybase, see documentation 11207 Log the processing of text and image datatypes from remote servers. Supported by Sybase, see documentation 11208 Prevents the create index and drop table statements from being transmitted to a remote server. sysindexes is updated anyway. Supported by Sybase, see documentation 11209 When running "update statistics" on remote tables update only the rowcount. Supported by Sybase, see documentation 11210 Disables Component Integration Services enhanced remote query optimization. 11211 Prevents the drop table syntax from being forwarded to remote servers if the table was created using the create table at location syntax. Supported by Sybase, see documentation 11212 Prevents escape on underscores in table names. Supported by Sybase, see documentation 11213 Prevents generation of column and table constraints. Supported by Sybase, see documentation 11214 Disables Component Integration Services recovery at start-up. Supported by Sybase, see documentation 11215 Sets enhanced remote optimization for servers of class db2. 11216 For the session, disables enhanced remote optimization. Supported by Sybase, see documentation 11217 For the server, disables enhanced remote optimization. Supported by Sybase, see documentation 11218 Any query that is part of a declare cursor command, and that references proxy tables, is read only by default. Supported by Sybase, see documentation 11220 Disables constraint checking of remote tables on the local server. This avoids duplicate checking. Setting this trace flag on ensures that queries are not rejected by the quickpass mode because of constraints. (spid) Supported by Sybase, see documentation 11221 Disables alter table commands to the remote server when ON. This allows users to modify type, length, and nullability of columns in a local table without changing columns in the remote table. Use trace flag 11221 with caution. It may lead to tables that are “out of sync.” (spid). Supported by Sybase, see documentation 11223 Disables proxy table index creation during create existing table or create proxy_table command execution. If this flag is set on, no index metadata is imported from the remote site referenced by the proxy table, and no indexes for the proxy table are created. This trace flag should be used with care and turned off when no longer necessary. (global) Supported by Sybase, see documentation 11228 A 2762 error, "CREATE TABLE command is not allowed within multiple statement transaction" may be reported when executing a SQL INSERT..SELECT from proxy table mapped to a RPC. This traceflag has to be turned on to allow CREATE TABLE command in the remote procedure (for the session) 11229 Use pre-12.5.3 behaviour to import statistics for proxy tables. Supported by Sybase, see documentation 11231 CIS: Connections to remote servers are not disconnected and remain engine affinitied until the client session terminates. The connections can now be dropped and detached from an engine after executing a statement to the remote server by enabling this flag. Exceptions are when the statement is participating in cursor, transaction or stored procedure operations; or when ASE is in either HA failover or failback states. 11232 A 2762 error, "CREATE TABLE command is not allowed within multiple statement transaction" may be reported when executing a SQL INSERT..SELECT from proxy table mapped to a RPC. This traceflag has to be turned on to allow CREATE TABLE command in the remote procedure (serverwide) 11299 Allows connection information to be logged when a connection to a remote server fails. Supported by Sybase, see documentation 11906 Informational messages from REORG will no longer be printed to the errorlog. 12628 Data insertion into DOL tables having nonclustered index will be done with the index prepend mode splits disabled, in order to improve disk space utilization. 15302 When a subquery appears in the ON clause of an outer join query, the performance may not be efficient. ASE will do optimization for subquery attachment to achieve more favorable performance when turned on. 15303 Possible performance improvement on a SELECT statement when a BIT column is involved in the WHERE clause. 15304 CR 422003: A SELECT statement using a LIKE clause with NULL variables returns Msg 712. Workaround for 'unable to allocate 0 bytes to heap' bug fixed in 12.5.3 ESD7. 15381 When set, the warning message 307, "Index specified as optimizer hint in the FROM clause of table does not exist. Optimizer will choose another index instead." is disabled. 15382 Disable "special OR strategy" (see release notes for the fine details) 15556 Allow dump and load in ASE cluster edition with multiple instances active
有关索引
--http://blog.csdn.net/dba_huangzj/article/category/1184123 --收集特定表上所有索引、堆的信息 SELECT sysIn.name AS IndexName , sysIn.index_id , func.avg_fragmentation_in_percent , func.index_type_desc AS IndexType , func.page_count FROM sys.dm_db_index_physical_stats(DB_ID(), OBJECT_ID(N'ordDemo'), NULL, NULL, NULL) AS func INNER JOIN sys.indexes AS sysIn ON func.object_id = sysIn.object_id AND func.index_id = sysIn.index_id order by sysIn.name,func.avg_fragmentation_in_percent --显示索引消耗的磁盘情况 SELECT CASE InnerTable.index_id WHEN 0 THEN 'HEAP' WHEN 1 THEN 'Clustered Index' ELSE 'Non-Clustered Index' END AS Index_Type , SUM(CASE WHEN FilledPage > PageToDeduct THEN ( FilledPage - PageToDeduct ) ELSE 0 END) * 8 Index_Size FROM ( SELECT partition_id , index_id , SUM(used_page_count) AS FilledPage , SUM(CASE WHEN ( index_id < 2 ) THEN ( in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count ) ELSE lob_used_page_count + row_overflow_used_page_count END) AS PageToDeduct FROM sys.dm_db_partition_stats GROUP BY partition_id , index_id ) AS InnerTable GROUP BY CASE InnerTable.index_id WHEN 0 THEN 'HEAP' WHEN 1 THEN 'Clustered Index' ELSE 'Non-Clustered Index' END GO --查找无用索引 SELECT ind.index_id , obj.name AS TableName , ind.name AS IndexName , ind.type_desc , indUsage.user_seeks , indUsage.user_scans , indUsage.user_lookups , indUsage.user_updates , indUsage.last_system_seek , indUsage.last_user_scan , 'drop index [' + ind.name + '] ON [' + obj.name + ']' AS DropIndexCommand FROM sys.indexes AS ind INNER JOIN sys.objects AS obj ON ind.object_id = obj.object_id LEFT JOIN sys.dm_db_index_usage_stats indUsage ON ind.object_id = indUsage.object_id AND ind.index_id = indUsage.index_id WHERE ind.type_desc <> 'HEAP' AND obj.type <> 'S' AND OBJECTPROPERTY(obj.object_id, 'isusertable') = 1 AND ( ISNULL(indUsage.user_seeks, 0) = 0 AND ISNULL(indUsage.user_scans, 0) = 0 AND ISNULL(indUsage.user_lookups, 0) = 0 ) ORDER BY obj.name , ind.name GO --查找丢失索引 SELECT avg_total_user_cost * avg_user_impact * ( user_scans + user_seeks ) AS PossibleImprovement , last_user_seek , last_user_scan , [statement] AS [Object] , 'CREATE INDEX [IDX_' + CONVERT(VARCHAR(32), GS.group_handle) + '_' + CONVERT(VARCHAR(32), D.index_handle) + '_' + REPLACE(REPLACE(REPLACE([STATEMENT], ']', ''), '[', ''), '.', '') + ']' + ' ON ' + [statement] + ' (' + ISNULL(equality_columns, '') + CASE WHEN equality_columns IS NOT NULL AND inequality_columns IS NOT NULL THEN ',' ELSE '' END + ISNULL(inequality_columns, '') + ')' + ISNULL(' INCLUDE (' + included_columns + ')', '') AS Create_Index_Syntax FROM sys.dm_db_missing_index_groups AS G INNER JOIN sys.dm_db_missing_index_group_stats AS GS ON G.index_group_handle = GS.group_handle INNER JOIN sys.dm_db_missing_index_details AS D ON G.index_handle = D.index_handle ORDER BY PossibleImprovement DESC /* --不指定参数重组索引: ALTER INDEX [idx_refno] ON [ordDemo] REORGANIZE GO --重组表中所有索引: ALTER INDEX ALL ON [ordDemo] REORGANIZE GO --使用DBCC INDEXDEFRAG重建表上所有索引: DBCC INDEXDEFRAG('AdventureWorks','ordDemo') GO --使用DBCC INDEXDEFRAG重组表上一个索引: DBCC INDEXDEFRAG('AdventureWorks','ordDemo','idx_refno') GO */
查看行数
select a.name as 表名,max(b.rows) as 记录条数 from sysobjects a ,sysindexes b where a.id=b.id and a.xtype='u' group by a.name order by max(b.rows) desc
SELECT Object_schema_name(p.object_id) AS [Schema], Object_name(p.object_id) AS [Table], i.name AS [Index], p.partition_number, p.rows AS [Row Count], i.type_desc AS [Index Type] FROM sys.partitions p INNER JOIN sys.indexes i ON p.object_id = i.object_id AND p.index_id = i.index_id WHERE Object_schema_name(p.object_id) <> 'sys' -- AND Object_name(p.object_id) = 'table_1' --获取某个表 ORDER BY [Schema], [Table], [Index]
查看使用情况
SELECT top 100 equality_columns,inequality_columns,included_columns,statement,avg_total_user_cost,avg_user_impact FROM sys.dm_db_missing_index_details as mid inner join sys.dm_db_missing_index_groups mig on mig.index_handle=mid.index_handle inner join sys.dm_db_missing_index_group_stats migs on mig.index_group_handle= migs.group_handle order by avg_total_user_cost desc

浙公网安备 33010602011771号