Search

Thursday, May 10, 2012

Look at currently executing requests, status and wait type

SELECT r.session_id, r.[status], r.wait_type, r.scheduler_id,

SUBSTRING(qt.[text],r.statement_start_offset/2,

(CASE WHEN r.statement_end_offset = -1

THEN LEN(CONVERT(nvarchar(max), qt.[text])) * 2

ELSE r.statement_end_offset

END - r.statement_start_offset)/2) AS [statement_executing],

DB_NAME(qt.[dbid]) AS [DatabaseName],

OBJECT_NAME(qt.objectid) AS [ObjectName],

r.cpu_time, r.total_elapsed_time, r.reads, r.writes,

r.logical_reads, r.plan_handle

FROM sys.dm_exec_requests AS r

CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS qt

WHERE r.session_id > 50

ORDER BY r.scheduler_id, r.[status], r.session_id;

Active Lock Manager Resources for Current Database

SELECT request_session_id, DB_NAME(resource_database_id) AS [Database],

resource_type, resource_subtype, request_type, request_mode,

resource_description, request_mode, request_owner_type

FROM sys.dm_tran_locks

WHERE request_session_id > 50

AND resource_database_id = DB_ID()

AND request_session_id <> @@SPID

ORDER BY request_session_id;

Findout blockings

SELECT tl.resource_type, tl.resource_database_id, tl.resource_associated_entity_id, tl.request_mode, tl.request_session_id, wt.blocking_session_id, wt.wait_type, wt.wait_duration_ms
FROM sys.dm_tran_locks as tl
INNER JOIN sys.dm_os_waiting_tasks as wt
ON tl.lock_owner_address = wt.resource_address
ORDER BY wait_duration_ms DESC;

Get a count of SQL connections by IP address

SELECT ec.client_net_address, es.[program_name],

es.[host_name], es.login_name,

COUNT(ec.session_id) AS [connection count]

FROM sys.dm_exec_sessions AS es

INNER JOIN sys.dm_exec_connections AS ec

ON es.session_id = ec.session_id

GROUP BY ec.client_net_address, es.[program_name], es.[host_name], es.login_name

ORDER BY ec.client_net_address, es.[program_name];

Physical CPU Count

SELECT cpu_count AS [Logical CPU Count], hyperthread_ratio AS [Hyperthread Ratio],

cpu_count/hyperthread_ratio AS [Physical CPU Count],

physical_memory_in_bytes/1048576 AS [Physical Memory (MB)],

sqlserver_start_time --, affinity_type_desc -- (affinity_type_desc is only in 2008 R2)

FROM sys.dm_os_sys_info OPTION (RECOMPILE);


Wednesday, May 9, 2012

Get logins that are connected and How many sessions they have

SELECT login_name, COUNT(session_id) AS [session_count]
FROM sys.dm_exec_sessions WITH (NOLOCK)
WHERE session_id > 50 -- filter out system SPIDs
GROUP BY login_name
ORDER BY COUNT(session_id) DESC OPTION (RECOMPILE);

Get processor description from Windows Registry

EXEC xp_instance_regread
'HKEY_LOCAL_MACHINE',
'HARDWARE\DESCRIPTION\System\CentralProcessor\0',
'ProcessorNameString';

Suggested Max Memory Settings for SQL Server 2005/2008

It is very important to make sure you set the Max Server memory setting for SQL Server 2005/2008 to something besides the default setting (which allows SQL Server to use as much memory as it wants, subject to signals from the operating system that it is under memory pressure). This is especially important with larger, busier systems that may be under memory pressure.

This setting controls how much memory can be used by the SQL Server Buffer Pool. If you don’t set an upper limit for this value, other parts of SQL Server, and the operating system can be starved for memory, which can cause instability and performance problems. It is even more important to set this correctly if you have “Lock Pages in Memory” enabled for the SQL Server service account (which I always do for x64 systems with more than 4GB of memory).

These settings are for x64, on a dedicated database server, only running the DB engine, (which is the ideal situation).

Physical RAM MaxServerMem Setting
2GB 1500
4GB 3200
6GB 4800
8GB 6400
12GB 10000
16GB 13500
24GB 21500
32GB 29000
48GB 44000
64GB 60000
72GB 68000
96GB 92000
128GB 124000

If you are running other SQL Server components, such as SSIS or Full Text Search, you will want to allocate less memory for the SQL Server Buffer Pool. You also want to pay close attention to how much memory is still available in Task Manager. This is how much RAM should be available in Task Manager while you are under load (on Windows Server 2003):

Physical RAM                   Target Avail RAM in Task Manager
< 4GB                                     512MB – 1GB
4-32GB                                  1GB – 2GB
32-128GB                              2GB – 4GB
> 128GB                                > 4GB

You can use T-SQL to set your MaxServerMemory setting. The sample below sets it to 3500, which is the equivalent of 3.5GB. This setting is dynamic in SQL Server 2005/2008, which means that you can change it and it goes into effect immediately, without restarting SQL Server.

– Turn on advanced options
EXEC sp_configure‘Show Advanced Options’,1;
GO
RECONFIGURE
;
GO

– Set max server memory = 3500MB for the server
EXEC sp_configure‘max server memory (MB)’,3500;
GO
RECONFIGURE
;
GO

-- See what the current values are

EXEC sp_configure;




Get CPU Utilization History for last 256 minutes

-- This version works with SQL Server 2008 and SQL Server 2008 R2 only

DECLARE @ts_now bigint = (SELECT cpu_ticks/(cpu_ticks/ms_ticks)FROM sys.dm_os_sys_info);


SELECT TOP(256) SQLProcessUtilization AS [SQL Server Process CPU Utilization],

               SystemIdle AS [System Idle Process],

               100 - SystemIdle - SQLProcessUtilization AS [Other Process CPU Utilization],

               DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) AS [Event Time]

FROM (

        SELECT record.value('(./Record/@id)[1]', 'int') AS record_id,

                  record.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int')

                  AS [SystemIdle],

                  record.value('(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]',

                  'int')

                  AS [SQLProcessUtilization], [timestamp]

        FROM (

                  SELECT [timestamp], CONVERT(xml, record) AS [record]

                  FROM sys.dm_os_ring_buffers WITH (NOLOCK)

                  WHERE ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR'

                  AND record LIKE N'%%') AS x

        ) AS y

ORDER BY record_id DESC OPTION (RECOMPILE);



 
-- Get CPU Utilization History (SQL 2005 Only)
 
 
DECLARE @ts_now bigint; 
SET @ts_now = (SELECT cpu_ticks / CONVERT(float, cpu_ticks_in_ms) FROM sys.dm_os_sys_info); 
 
SELECT TOP(256) SQLProcessUtilization AS [SQL Server Process CPU Utilization], 
               SystemIdle AS [System Idle Process], 
               100 - SystemIdle - SQLProcessUtilization AS [Other Process CPU Utilization], 
               DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) AS [Event Time] 
FROM ( 
          SELECT record.value('(./Record/@id)[1]', 'int') AS record_id, 
                       record.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int') 
                       AS [SystemIdle], 
                       record.value('(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]', 
                       'int') 
                       AS [SQLProcessUtilization], [timestamp] 
          FROM ( 
                       SELECT [timestamp], CONVERT(xml, record) AS [record] 
                       FROM sys.dm_os_ring_buffers 
                       WHERE ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR' 
                       AND record LIKE '%%') AS x 
          ) AS y 
ORDER BY record_id DESC OPTION (RECOMPILE);
 








When were Statistics last updated on all indexes


SELECT o.name, i.name AS [Index Name], 

       STATS_DATE(i.[object_id], i.index_id) AS [Statistics Date],

       s.auto_created, s.no_recompute, s.user_created

FROM sys.objects AS o WITH (NOLOCK)

INNER JOIN sys.indexes AS i WITH (NOLOCK)

ON o.[object_id] = i.[object_id]

INNER JOIN sys.stats AS s WITH (NOLOCK)

ON i.[object_id] = s.[object_id]

AND i.index_id = s.stats_id

WHERE o.[type] = 'U'

ORDER BY STATS_DATE(i.[object_id], i.index_id) ASC OPTION (RECOMPILE);     

Get CPU Utilization by Database

WITH DB_CPU_Stats
AS
(SELECT DatabaseID, DB_Name(DatabaseID) AS [DatabaseName], SUM(total_worker_time) AS [CPU_Time_Ms]
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY (SELECT CONVERT(int, value) AS [DatabaseID]
              FROM sys.dm_exec_plan_attributes(qs.plan_handle)
              WHERE attribute = N'dbid') AS F_DB
GROUP BY DatabaseID)
SELECT ROW_NUMBER() OVER(ORDER BY [CPU_Time_Ms] DESC) AS [row_num],
       DatabaseName, [CPU_Time_Ms],
       CAST([CPU_Time_Ms] * 1.0 / SUM([CPU_Time_Ms]) OVER() * 100.0 AS DECIMAL(5, 2)) AS [CPUPercent]
FROM DB_CPU_Stats
WHERE DatabaseID > 4 -- system databases
AND DatabaseID <> 32767 -- ResourceDB
ORDER BY row_num OPTION (RECOMPILE);

Maintenance DBCC Commands

Maintenance DBCC statements are used to gather information about the general health of the database as well as specific database objects and to repair minor database corruption issues.

•DBCC CHECKALLOC
•DBCC CHECKCATALOG
•DBCC CHECKCONSTRAINTS
•DBCC CHECKDB
•DBCC CHECKFILEGROUP
•DBCC CHECKTABLE
•DBCC CLEANTABLE

•DBCC DBREINDEX
•DBCC INDEXDEFRAG
•DBCC NEWALLOC
•DBCC SHOWCONTIG
•DBCC SHOW_STATISTICS
•DBCC SHRINK_DATABASE
•DBCC SHRINKFILE

Tuesday, May 8, 2012

Move Tables Between The File Groups

1.Check  Table is exist on which filegroup

SELECT d.name AS FileGroup
 FROM sys.filegroups d
 JOIN sys.indexes i
   ON i.data_space_id = d.data_space_id
 JOIN sys.tables t
   ON t.object_id = i.object_id
WHERE i.index_id<2                     -- could be heap or a clustered table
 AND t.name= 'Employee'
 AND t.schema_id = schema_id('HumanResources')

Add another data file to the database in a separate file group.Then create the index by running the below query.

2.Create Index

CREATE UNIQUE CLUSTERED INDEX PK_Employee
    ON HumanResources.Employee(LoginID)
    WITH (DROP_EXISTING = ON) ON [Test_Data_2]

 CREATE CLUSTERED INDEX PK_Employee
    ON HumanResources.Employee(LoginID)
    WITH (DROP_EXISTING = ON) ON [Test_Data_2]

Then again execute the query-1.You will noticed the table is now pointing to the second datafile.

Wednesday, March 21, 2012

Steps to Save/Store file into Database

You can use the below scripts to store/save the file into SQL Server database table. Please note it is not recommended to store file into database. You can store the file on file system and path in the database.

use Testing
--documents table will store files into varbinary field
--drop table documents
create table documents
(
    documentID int identity(1,1),
    doctype char(5),
    document varbinary(max)
)
--script to store/save document into table
insert into documents
 Select 'xls', (SELECT * FROM OPENROWSET(BULK N'C:\LeaveHistoryReport.xls', SINGLE_BLOB) AS document) document
go
select * from documents

Transactions and Locks in SQL Server

• What is a “Database Transactions “?
A database transaction is a unit of work performed against a database management system or similar system that is treated in a coherent and reliable way independent of other transactions. A database transaction, by definition, must be atomic, consistent, isolated and durable. These properties of database transactions are often referred to by the acronym ACID.
Transactions provide an “all-or-nothing” proposition stating that work units performed in a database must be completed in their entirety or take no effect whatsoever. Further, transactions must be isolated from other transactions, results must conform to existing constraints in the database and transactions that complete successfully must be committed to durable storage.
In some systems, transactions are also called LUWs for Logical Units of Work.
• What is ACID?
The ACID model is one of the oldest and most important concepts of database theory. It sets forward four goals that every database management system must strive to achieve: atomicity, consistency, isolation and durability. No database that fails to meet any of these four goals can be considered reliable.
Let’s take a moment to examine each one of these characteristics in detail:
Atomicity states that database modifications must follow an “all or nothing” rule. Each transaction is said to be “atomic.” If one part of the transaction fails, the entire transaction fails. It is critical that the database management system maintain the atomic nature of transactions in spite of any DBMS, operating system or hardware failure.
Consistency states that only valid data will be written to the database.If, for some reason, a transaction is executed that violates the database’s consistency rules, the entire transaction will be rolled back and the database will be restored to a state consistent with those rules. On the other hand, if a transaction successfully executes, it will take the database from one state that is consistent with the rules to another state that is also consistent with the rules.
Isolation requires that multiple transactions occurring at the same time not impact each other’s execution. For example, if Joe issues a transaction against a database at the same time that Mary issues a different transaction, both transactions should operate on the database in an isolated manner. The database should either perform Joe’s entire transaction before executing Mary’s or vice-versa. This prevents Joe’s transaction from reading intermediate data produced as a side effect of part of Mary’s transaction that will not eventually be committed to the database. Note that the isolation property does not ensure which transaction will execute first, merely that they will not interfere with each other.
Durability ensures that any transaction committed to the database will not be lost. Durability is ensured through the use of database backups and transaction logs that facilitate the restoration of committed transactions in spite of any subsequent software or hardware failures.
• What is “Begin Trans”, “Commit Tran”, “Rollback Tran” and “Save Tran”?
Transactions group a set of tasks into a single execution unit. Each transaction begins with a specific task and ends when all the tasks in the group successfully complete. If any of the tasks fails, the transaction fails. Therefore, a transaction has only two results: success or failure. Incomplete steps result in the failure of the transaction.
Users can group two or more Transact-SQL statements into a single transaction using the following statements:
* Begin Transaction
* Rollback Transaction
* Commit Transaction
Begin Transaction
Marks the starting point of an explicit, local transaction. BEGIN TRANSACTION increments @@TRANCOUNT by 1.
Rollback Transaction
If anything goes wrong with any of the grouped statements, all changes need to be aborted. The process of reversing changes is called rollback in SQL Server terminology.
A ROLLBACK, on the other hand, works regardless of the level at which it is issued, but rolls back all transactions, regardless of the nesting level
Commit Transaction
If everything is in order with all statements within a single transaction, all changes are recorded together in the database. In SQL Server terminology, we say that these changes are committed to the database.
A COMMIT issued against any transaction except the outermost one doesn’t commit any changes to disk – it merely decrements the@@TRANCOUNT automatic variable.
Save Tran
Savepoints offer a mechanism to roll back portions of transactions. A user can set a savepoint, or marker, within a transaction. The savepoint defines a location to which a transaction can return if part of the transaction is conditionally canceled. SQL Server allows you to use savepoints via the SAVE TRAN statement, which doesn’t affect the @@TRANCOUNT value. A rollback to a savepoint (not a transaction) doesn’t affect the value returned by @@TRANCOUNT, either. However, the rollback must explicitly name the savepoint: using ROLLBACK TRAN without a specific name will always roll back the entire transaction.
• What are “Checkpoint’s” in SQL Server?
Forces all dirty pages for the current database to be written to disk. Dirty pages are data or log pages modified after entered into the buffer cache, but the modifications have not yet been written to disk.
Syntax
CHECKPOINT
• What are “Implicit Transactions”?
Microsoft SQL Server operates in three transaction modes:
Autocommit transactions
Each individual statement is a transaction.
Explicit transactions
Each transaction is explicitly started with the BEGIN TRANSACTION statement and explicitly ended with a COMMIT or ROLLBACK statement.
Implicit transactions
A new transaction is implicitly started when the prior transaction completes, but each transaction is explicitly completed with a COMMIT or ROLLBACK statement.
• Is it good to use “Implicit Transactions”?
If you want all your commands to require an explicit COMMIT or ROLLBACK in order to finish, you can issue the command SET IMPLICIT_TRANSACTIONS ON. By default, SQL Server operates in the autocommit mode; it does not operate with implicit transactions. Any time you issue a data modification command such as INSERT, UPDATE, or DELETE, SQL Server automatically commits the transaction. However, if you use the SET IMPLICIT_TRANSACTIONS ON command, you can override the automatic commitment so that SQL Server will wait for you to issue an explicit COMMIT or ROLLBACK statement to do anything with the transaction. This can be handy when you issue commands interactively, mimicking the behavior of other databases such as Oracle.
What’s distinctive about implicit transactions is that reissuing SET IMPLICIT_TRANSACTIONS ON does not increase the value of @@TRANCOUNT. Also, neither COMMIT nor ROLLBACK reduce the value of @@TRANCOUNT until after you issue the command SET IMPLICIT_TRANSACTIONS OFF. Developers do not often use implicit transactions; however, there is an interesting exception in ADO. See the sidebar, Implicit Transactions and ADO Classic.
• What is Concurrency?
When many people attempt to modify data in a database at the same time, a system of controls must be implemented so that modifications made by one person do not adversely affect those of another person. This is called concurrency control.
Concurrency control theory has two classifications for the methods of instituting concurrency control:
Pessimistic concurrency control
A system of locks prevents users from modifying data in a way that affects other users. After a user performs an action that causes a lock to be applied, other users cannot perform actions that would conflict with the lock until the owner releases it. This is called pessimistic control because it is mainly used in environments where there is high contention for data, where the cost of protecting data with locks is less than the cost of rolling back transactions if concurrency conflicts occur.
Optimistic concurrency control
In optimistic concurrency control, users do not lock data when they read it. When an update is performed, the system checks to see if another user changed the data after it was read. If another user updated the data, an error is raised. Typically, the user receiving the error rolls back the transaction and starts over. This is called optimistic because it is mainly used in environments where there is low contention for data, and where the cost of occasionally rolling back a transaction outweighs the costs of locking data when read.
• What are “Dirty reads”?
Uncommitted dependency occurs when a second transaction selects a row that is being updated by another transaction. The second transaction is reading data that has not been committed yet and may be changed by the transaction updating the row.
• What are “Unrepeatable reads”?
Inconsistent Analysis (Nonrepeatable Read)
Inconsistent analysis occurs when a second transaction accesses the same row several times and reads different data each time. Inconsistent analysis is similar to uncommitted dependency in that another transaction is changing the data that a second transaction is reading. However, in inconsistent analysis, the data read by the second transaction was committed by the transaction that made the change. Also, inconsistent analysis involves multiple reads (two or more) of the same row and each time the information is changed by another transaction; thus, the term nonrepeatable read.
• What are “Phantom rows”?
Phantom reads occur when an insert or delete action is performed against a row that belongs to a range of rows being read by a transaction. The transaction’s first read of the range of rows shows a row that no longer exists in the second or succeeding read, as a result of a deletion by a different transaction. Similarly, as the result of an insert by a different transaction, the transaction’s second or succeeding read shows a row that did not exist in the original read.
For example, an editor makes changes to a document submitted by a writer, but when the changes are incorporated into the master copy of the document by the production department, they find that new unedited material has been added to the document by the author. This problem could be avoided if no one could add new material to the document until the editor and production department finish working with the original document.
• What are “Lost Updates”?
Lost updates occur when two or more transactions select the same row and then update the row based on the value originally selected. Each transaction is unaware of other transactions. The last update overwrites updates made by the other transactions, which results in lost data.
• What are different levels of granularity of locking resources?
Microsoft SQL Server 2000 has multigranular locking that allows different types of resources to be locked by a transaction. To minimize the cost of locking, SQL Server locks resources automatically at a level appropriate to the task. Locking at a smaller granularity, such as rows, increases concurrency, but has a higher overhead because more locks must be held if many rows are locked. Locking at a larger granularity, such as tables, are expensive in terms of concurrency because locking an entire table restricts access to any part of the table by other transactions, but has a lower overhead because fewer locks are being maintained.
SQL Server can lock these resources (listed in order of increasing granularity).
RID: Row identifier. Used to lock a single row within a table.
Key: Row lock within an index. Used to protect key ranges in serializable transactions.
Page: 8 kilobyte –(KB) data page or index page.
Extent: Contiguous group of eight data pages or index pages.
Table: Entire table, including all data and indexes.
DB: Database.
• What are different types of Isolation levels in SQL Server?
READ COMMITTED
Specifies that shared locks are held while the data is being read to avoid dirty reads, but the data can be changed before the end of the transaction, resulting in nonrepeatable reads or phantom data. This option is the SQL Server default.
READ UNCOMMITTED
Implements dirty read, or isolation level 0 locking, which means that no shared locks are issued and no exclusive locks are honored. When this option is set, it is possible to read uncommitted or dirty data; values in the data can be changed and rows can appear or disappear in the data set before the end of the transaction. This option has the same effect as setting NOLOCK on all tables in all SELECT statements in a transaction. This is the least restrictive of the four isolation levels.
REPEATABLE READ
Locks are placed on all data that is used in a query, preventing other users from updating the data, but new phantom rows can be inserted into the data set by another user and are included in later reads in the current transaction. Because concurrency is lower than the default isolation level, use this option only when necessary.
SERIALIZABLE
Places a range lock on the data set, preventing other users from updating or inserting rows into the data set until the transaction is complete. This is the most restrictive of the four isolation levels. Because concurrency is lower, use this option only when necessary. This option has the same effect as setting HOLDLOCK on all tables in all SELECT statements in a transaction.
• If you are using COM+, what “Isolation” level is set by default?
SERIALIZABLE transaction isolation level is the default isolation level for the COM+ application.
• What are “Lock” hints?
A range of table-level locking hints can be specified using the SELECT, INSERT, UPDATE, and DELETE statements to direct Microsoft SQL Server 2000 to the type of locks to be used. Table-level locking hints can be used when a finer control of the types of locks acquired on an object is required. These locking hints override the current transaction isolation level for the session.
• What is a “Deadlock”?
Deadlocking occurs when two user processes have locks on separate objects and each process is trying to acquire a lock on the object that the other process has. When this happens, SQL Server identifies the problem and ends the deadlock by automatically choosing one process and aborting the other process, allowing the other process to continue. The aborted transaction is rolled back and an error message is sent to the user of the aborted process. Generally, the transaction that requires the least amount of overhead to rollback is the transaction that is aborted.
• What are the steps you can take to avoid “Deadlocks”?
Here are some tips on how to avoid deadlocking on your SQL Server:
* Ensure the database design is properly normalized.
* Have the application access server objects in the same order each time.
* During transactions, don’t allow any user input. Collect it before the transaction begins.
* Avoid cursors.
* Keep transactions as short as possible. One way to help accomplish this is to reduce the number of round trips between your application and SQL Server by using stored procedures or keeping transactions with a single batch. Another way of reducing the time a transaction takes to complete is to make sure you are not performing the same reads over and over again. If your application does need to read the same data more than once, cache it by storing it in a variable or an array, and then re-reading it from there, not from SQL Server.
* Reduce lock time. Try to develop your application so that it grabs locks at the latest possible time, and then releases them at the very earliest time.
* If appropriate, reduce lock escalation by using the ROWLOCK or PAGLOCK.
* Consider using the NOLOCK hint to prevent locking if the data being locked is not modified often.
* If appropriate, use as low of an isolation level as possible for the user connection running the transaction.
* Consider using bound connections.
• What is Bound Connection?
Bound connections allow two or more connections to share the same transaction and locks. Bound connections can work on the same data without lock conflicts. Bound connections can be created from multiple connections within the same application, or from multiple applications with separate connections. Bound connections make coordinating actions across multiple connections easier.
To participate in a bound connection, a connection calls sp_getbindtoken or srv_getbindtoken (Open Data Services) to get a bind token. A bind token is a character string that uniquely identifies each bound transaction. The bind token is then sent to the other connections participating in the bound connection. The other connections bind to the transaction by calling sp_bindsession, using the bind token received from the first connection.
• Specity the types of Bound Connections
Local bound connection
Allows bound connections to share the transaction space of a single transaction on a single server.
Distributed bound connection
Allows bound connections to share the same transaction across two or more servers until the entire transaction is either committed or rolled back by using Microsoft Distributed Transaction Coordinator (MS DTC).
• How can I know what locks are running on which resource?
Use SP_Locks system stored procedure

Troubleshoot Suspect Database Issue

Solution:

Step 1: Bring the database online using below script

USE Master

GO



– Determine the original database status

SELECT [Name], DBID, Status

FROM master.dbo.sysdatabases

GO



– Enable system changes

sp_configure ‘allow updates’,1

GO

RECONFIGURE WITH OVERRIDE

GO
–- Update the database status

UPDATE master.dbo.sysdatabases

SET Status = 24

WHERE [Name] = ‘SuspectedDatabaseName’

GO



–- Disable system changes

sp_configure ‘allow updates’,0

GO

RECONFIGURE WITH OVERRIDE

GO

-– Determine the final database status

SELECT [Name], DBID, Status

FROM master.dbo.sysdatabases

GO

Step 2: Check for database corruption. This is very important step please execute it.

 ■DBCC CHECKDB – Validate the overall database integrity
 ■DBCC CHECKCATALOG – Validate the system catalog integrity
 ■DBCC CHECKTABLE – Validate the integrity for a single table

Step 3: To resolve the corruption issue, please execute below commands

 ■Drop and Recreate Index(es)
 ■Move the recoverable data from an existing table to a new table
 ■Update statistics
 ■DBCC UPDATEUSAGE
 ■sp_recompile

Step 4: Repeat Step 2 to validate all the corruption occurred.

Database Administration Scripts

 – Create databsae TEST

 CREATE DATABASE [TEST] ON PRIMARY
 ( NAME = N’TEST’, FILENAME = N’C:\TEST.mdf’ , SIZE = 2048KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
 LOG ON
 ( NAME = N’TEST_log’, FILENAME = N’C:\TEST_log.ldf’ , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
 COLLATE SQL_Latin1_General_CP1_CI_AS
 GO

–Script to create schema

 USE [TEST]
 GO
 CREATE SCHEMA [myTEST] AUTHORIZATION [dbo]

– Script to create table with constraints

 create table myTEST.Emp
 (
 EmpID int Primary key identity(100,1),
 EmpName Varchar(20) Constraint UK1 Unique,
 DOB datetime Not Null,
 JoinDate datetime default getdate(),
 Age int Constraint Ck1 Check (Age > 18)
 )

– Script to change the recovery model of the databsae

 USE [master]
 GO
 ALTER DATABASE [TEST] SET RECOVERY FULL WITH NO_WAIT
 GO

ALTER DATABASE [TEST] SET RECOVERY FULL
 GO

– Script to take the full backup of database

 BACKUP DATABASE [TEST] TO DISK = N’D:\TEST.bak’
 WITH NOFORMAT, INIT, NAME = N’TEST-Full Database Backup’,
 NOREWIND, SKIP, NOUNLOAD, STATS = 10
 GO

–Script to take the Differential Database backup

 BACKUP DATABASE [TEST] TO DISK = N’D:\TEST.diff.bak’
 WITH DIFFERENTIAL , NOFORMAT, INIT, NAME = N’TEST-Diff Backup’,
 NOREWIND, SKIP, NOUNLOAD, STATS = 10
 GO

–Script to take the Transaction Log backup that truncates the log

 BACKUP LOG [TEST] TO DISK = N’D:\TESTTlog.trn’
 WITH NOFORMAT, INIT, NAME = N’TEST-Transaction Log Backup’,SKIP, NOREWIND, NOUNLOAD, STATS = 10
 GO

– Backup the tail of the log (not normal procedure)

 BACKUP LOG [TEST] TO DISK = N’D:\TESTLog.tailLog.trn’
 WITH NO_TRUNCATE , NOFORMAT, INIT, NAME = N’TEST-Transaction Log Backup’,NOREWIND,SKIP, NOUNLOAD, NORECOVERY , STATS = 10
 GO

– Script to Get the backup file properties

 RESTORE FILELISTONLY FROM DISK = ‘D:\TEST.bak’

– Script to Restore Full Database Backup

 RESTORE DATABASE [TEST1] FROM DISK = N’D:\TEST.bak’
 WITH FILE = 1, MOVE N’TEST’ TO N’D:\TESTdata.mdf’,
 MOVE N’TEST_log’ TO N’D:\TESTlog_1.ldf’,
 NOUNLOAD, STATS = 10
 GO

– Script to delete the backup history of the specific databsae

 EXEC msdb.dbo.sp_delete_database_backuphistory @database_name = N’TEST1′
 GO

– Full restore with no recovery (status will be Restoring)

 RESTORE DATABASE [TEST1] FROM DISK = N’D:\TEST.bak’
 WITH FILE = 1, MOVE N’TEST’ TO N’D:\TESTdata.mdf’,
 MOVE N’TEST_Log’ TO N’D:\TESTLog_1.ldf’,
 NORECOVERY, NOUNLOAD, STATS = 10
 GO

– Restore transaction log with recovery

 RESTORE LOG [TEST1] FROM DISK = N’D:\TESTLog.trn’
 WITH FILE = 1, NOUNLOAD, RECOVERY STATS = 10
 GO

–Script to bring the database online without restoring log backup

 restore database TEST with recovery

–Script to detach database

 USE [master]
 GO
 EXEC master.dbo.sp_detach_db @dbname = N’TEST’
 GO

– Script to get the database information

 sp_helpdb ‘TEST’

–to Attach database

 USE [master]
 GO

CREATE DATABASE [TEST1] ON
 ( FILENAME = N’C:\TEST.mdf’ ),
 ( FILENAME = N’C:\TEST_Log.ldf’ )
 FOR ATTACH
 GO

USE TEST
 GO

– Get Fragmentation info for each non heap table in TEST database
 – Avg frag.in percent is External Fragmentation (above 10% is bad)
 – Avg page space used in percent is Internal Fragmention (below 75% is bad)

SELECT OBJECT_NAME(dt.object_id) AS ‘Table Name’ , si.name AS ‘Index Name’,
 dt.avg_fragmentation_in_percent, dt.avg_page_space_used_in_percent
 FROM
 (SELECT object_id, index_id, avg_fragmentation_in_percent, avg_page_space_used_in_percent
 FROM sys.dm_db_index_physical_stats (DB_ID(‘TEST’), NULL, NULL, NULL, ‘DETAILED’)
 WHERE index_id <> 0) AS dt
 INNER JOIN sys.indexes AS si
 ON si.object_id = dt.object_id
 AND si.index_id = dt.index_id
 ORDER BY OBJECT_NAME(dt.object_id)

– Script to Get Fragmention information for a single table

 SELECT TableName = object_name(object_id), database_id, index_id, index_type_desc, avg_fragmentation_in_percent, fragment_count, page_count
 FROM sys.dm_db_index_physical_stats (DB_ID(N’TEST’), OBJECT_ID(N’myTEST.Emp’), NULL, NULL , ‘LIMITED’);

–script to get the index information

 exec sp_helpindex [myTEST.Emp]

–Script to Reorganize an index

 ALTER INDEX PK_ProductPhoto_ProductPhotoID ON Production.ProductPhoto
 REORGANIZE
 GO

– Rebuild an index (offline mode)

 ALTER INDEX ALL ON Production.Product
 REBUILD WITH (FILLFACTOR = 80, SORT_IN_TEMPDB = ON,STATISTICS_NORECOMPUTE = ON);

–Script to find which columns don’t have statistics

 SELECT c.name AS ‘Column Name’
 FROM sys.columns AS c
 LEFT OUTER JOIN sys.stats_columns AS sc
 ON sc.[object_id] = c.[object_id]
 AND sc.column_id = c.column_id
 WHERE c.[object_id] = OBJECT_ID(‘myTEST.Emp’)
 AND sc.column_id IS NULL
 ORDER BY c.column_id

– Create Statistics on DOB column

 CREATE STATISTICS st_BirthDate
 ON myTEST.Emp(DOB)
 WITH FULLSCAN

– When were statistics on indexes last updated

 SELECT 'Index Name' = i.name, 'Statistics Date' = STATS_DATE(i.object_id, i.index_id)
 FROM sys.objects AS o WITH (NOLOCK)
 JOIN sys.indexes AS i WITH (NOLOCK)
 ON o.name = 'Emp'
 AND o.object_id = i.object_id
 ORDER BY STATS_DATE(i.object_id, i.index_id);

– Update statistics on all indexes in the table

 UPDATE STATISTICS myTEST.Emp
 WITH FULLSCAN

– Script to shrink database

 DBCC SHRINKDATABASE(N’TEST’ )
 GO

– Shrink data file (truncate only)

 DBCC SHRINKFILE (N’TEST_Data’ , 0, TRUNCATEONLY)
 GO

– Script to shrink Shrink data file – Very Slow and Enhances the fragmentation

 DBCC SHRINKFILE (N’TEST_Data’ , 10)
 GO
 – Script Shrink transaction log file

 DBCC SHRINKFILE (N’TEST_Log’ , 0, TRUNCATEONLY)
 GO

– Script to create view

 CREATE VIEW emp_view
 AS
 SELECT *
 FROM myTEST.emp

Script to Rename Database

CREATE DATABASE Test

 –Solution - I

 EXEC Sp_renamedb  ‘Test’,  ‘Testing’

–Solution - II

 ALTER DATABASE Test MODIFY name=Testing