You are on page 1of 211

Issue Details

Wednesday, September 11, 2013

4:13:03 AM

Issue 4: To Take Backup of Database with NICER file name - REPLACE(REPLACE(CONVERT(Varchar(40), GETDATE(), 120),'','_'),':','_') + '.bak'; Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-May-10 Backup and Restore 25-May-10

G(0)

Description
--Full backup using nicer file name DECLARE @devname varchar(256) SELECT @devname = 'C:\BACKUP\AdventureWorks2008_Full_' + REPLACE(REPLACE(CONVERT(Varchar(40), GETDATE(), 120),'-','_'),':','_') + '.bak'; BACKUP DATABASE AdventureWorks2008 to DISK = @devname with comression,stats=1

Comments Issue 5: To Restore a database Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-May-10 Backup and Restore

G(0)

Description ALTER DATABASE DataBaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE


RESTORE FILELISTONLY FROM DISK = '' RESTORE DATABASE DataBaseName FROM DISK = '' WITH STATS = 1,REPLACE, MOVE '' TO '', MOVE '' TO '' Replace --move ---

Comments

Page 1 of 211

Issue 6: user reported error Error number : 2760 and 4902 while creating table on database. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-May-10 Login_User_Schema

G(0)

Description USE [master] GO CREATE LOGIN [DHC\SVIDDCPT] FROM WINDOWS WITH DEFAULT_DATABASE=[catalog_dev] GO
use [catalog_dev] go create user [DHC\SVIDDCPT] for login [DHC\SVIDDCPT] go

Then given

USE [Catalog_dev] go GRANT CREATE PROCEDURE TO [DHC\APP-DCP-DEV] go GRANT CREATE FUNCTION TO [DHC\APP-DCP-DEV] go Grant CREATE Table to [DHC\APP-DCP-DEV] Assuming I have given grant Create table access so user can create table then asked user to create Table in the database [catalog_dev] user reported error Error number : 2760 and 4902.

Msg 2760, Level 16, State 1, Line 1 The specified schema name "dbo" either does not exist or you do not have permission to use it. Msg 4902, Level 16, State 1, Line 4 Cannot find the object "dbo.CRTV_PROJ" because it does not exist or you do not have permissions. Then executed the command

GRANT ALTER ON SCHEMA::dbo TO [DHC\APP-DCP-DEV] Then both Error 2760 and 4902 resolved.

Comments

Page 2 of 211

Issue 7: Users Mapping Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-May-10 Login_User_Schema

G(0)

Description USE [DBName]


EXECUTE SP_Change_Users_Login 'Update_One',LoginName,UserName ---------------------------------------------------------------------------------select 'Execute SP_Change_Users_Login ''Update_One'',['+name+'],['+name+']' from sysusers where name not like 'db_%' and name not in ('dbo','sys','guest','INFORMATION_SCHEMA','public') --------------------------------------------------------------------------------select ' Exec SP_AddRoleMember DB_DataReader,['+name+']' from sysusers where name not like 'db_%' and name not in ('dbo','sys','guest','INFORMATION_SCHEMA','public') ---------------------------------------------------

Comments
Issue 8: Schema Creation and granting permission to bind user of schema Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-May-10 Login_User_Schema

G(0)

Description CREATE SCHEMA SchemaName AUTHORIZATION userName


GRANT GRANT GRANT GRANT CREATE CREATE CREATE CREATE TABLE TO userName VIEW TO userName PROCEDURE TO userName FUNCTION TO userName

Comments

Page 3 of 211

Issue 9: Query to get all session information Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-May-10 Query-Session Level

G(0)

Description SELECT session_id, TEXT FROM sys.dm_exec_connections CROSS APPLY sys.dm_exec_sql_text(most_recent_sql_handle) AS ST Comments Issue 10: To Check how much percentage of data restored/backup- and log restores -log backuped - sys.dm_exec_request & sys.sysdatabases Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-May-10 Backup and Restore

G(0)

Description select d.name, percent_complete, dateadd(second,estimated_completion_time/1000, getdate()), Getdate() as now, datediff(minute, start_time, getdate()) as running, estimated_completion_time/1000/60 as togo, start_time, command from sys.dm_exec_requests req inner join sys.sysdatabases d on d.dbid = req.database_id where req.command in ('RESTORE DATABASE', 'BACKUP DATABASE', 'RESTORE LOG', 'BACKUP LOG')
or When file is last restored we can get it from msdb.dbo.restorefilehistory..

Comments

Page 4 of 211

Issue 11: Recover database from suspect mode Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-May-10 Corruption

G(0)

Description
sp_resetstatus turns off the suspect flag on a database. This procedure updates the mode and status columns of the named database in sys.databases. The SQL Server error log should be consulted and all problems resolved before running this procedure. Stop and restart the instance of SQL Server after you execute sp_resetstatus. A database can become suspect for several reasons. Possible causes include denial of access to a database resource by the operating system, and the unavailability or corruption of one or more database files. USE master GO EXEC sp_resetstatus 'bad DatabaseName' GO USE DatabaseName DBCC CHECKDB WITH NO_INFOMSGS GO USE master GO ALTER DATABASE DatabaseName SET EMERGENCY GO ALTER DATABASE DatabaseName SET SINGLE_USER GO DBCC CHECKDB (DatabaseName, REPAIR_ALLOW_DATA_LOSS) WITH NO_INFOMSGS GO USE DatabaseName DBCC CHECKDB WITH NO_INFOMSGS GO

Comments Issue 12: Query to get all session information - sys.dm_exec_connections Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-May-10 Query-Session Level 26-May-10

G(0)

Description SELECT session_id, TEXT FROM sys.dm_exec_connections CROSS APPLY sys.dm_exec_sql_text(most_recent_sql_handle) AS ST Comments

Page 5 of 211

Issue 13: Drop Statement for droping user objects Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-May-10 Query-Session Level 26-May-10

G(0)

Description SELECT 'DROP '+ CASE TYPE_DESC WHEN 'USER_TABLE' THEN 'TABLE ' WHEN 'VIEW' THEN 'VIEW ' WHEN 'SQL_STORED_PROCEDURE' THEN 'PROCEDURE ' WHEN 'SQL_INLINE_TABLE_VALUED_FUNCTION' THEN 'FUNCTION ' WHEN 'SQL_SCALAR_FUNCTION' THEN 'FUNCTION ' WHEN 'SQL_TABLE_VALUED_FUNCTION' THEN 'FUNCTION ' END + SCHEMA_NAME(SCHEMA_ID)+'.['+NAME+']' AS 'DROP STATEMENT' FROM SYS.OBJECTS WHERE SCHEMA_NAME(SCHEMA_ID) IN ('SCHEMA_NAME')-- Schema name who's objects need to be dropped. AND TYPE_DESC IN ('USER_TABLE', 'VIEW', 'SQL_STORED_PROCEDURE', 'SQL_INLINE_TABLE_VALUED_FUNCTION', 'SQL_SCALAR_FUNCTION', 'SQL_TABLE_VALUED_FUNCTION') ORDER BY SCHEMA_NAME(SCHEMA_ID), TYPE_DESC Comments

Page 6 of 211

Issue 14: Rebuilding Master Database in Clustered Server Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-May-10 Corruption

G(0)

Description start /wait setup.exe /qn VS=<VSName> INSTANCENAME=<InstanceName> REINSTALL=SQL_Engine REBUILDDATABASE=1 ADMINPASSWORD=<StrongPassword> SAPWD=<NewStrongPassword> SQLACCOUNT=<domain\user> SQLPASSWORD=<DomainUserPassword> AGTACCOUNT=<domain\user> AGTPASSWORD=<DomainUserPassword>
Example :start /wait <cd or dvd drive>\setup.exe /qn VS="p-sql-XXXXX" INSTANCENAME=PXXU01 GROUP="SQL Group - PCSXX01" REINSTALL=SQL_Engine REBUILDDATABASE=1 ADMINPASSWORD=Passw0rd1 SAPWD=Passw0rd SQLCOLLATION=SQL_Latin1_General_CP1_CI_AS SQLACCOUNT=Domain\CSXXXXXDMINA SQLPassword=Passw0rd AGTACCOUNT=Domain\CSXXXXXDMINA AGTPASSWORD=Passw0rd

Comments

Page 7 of 211

Issue 15: Cluster Information- ComputerNamePhysicalNetBIOS - Sys.dm_os_cluster_nodes - cluster_shared_drives Category Status Priority Attachments (1) Category Active (1) High Assigned To Due Date Opened By Opened Date 25-May-10 Cluster 26-May-10

G(0)

Description SELECT SERVERPROPERTY('ComputerNamePhysicalNetBIOS')-- currently which node are in preferred owner.


SELECT * FROM sys.dm_os_cluster_nodes -- Nodes in a cluster via Query Analyser? SELECT * FROM sys.dm_io_cluster_shared_drives SELECT * FROM ::FN_VIRTUALSERVERNODES() -- Nodes in a cluster via Query Analyser? -- it is for sql server 2000 Select serverproperty('IsClustered')

-- Check the server is in Cluster or not.

Server instance is configured in a failover cluster. 1 = Clustered. 0 = Not Clustered. NULL = Input is not valid, or an error. Base data type: int SELECT CONVERT(char(20), SERVERPROPERTY('ComputerNamePhysicalNetBIOS'));

Comments

Page 8 of 211

Issue 16: Getting Last Backup information Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-May-10 Backup and Restore

G(0)

Description SELECT CONVERT(CHAR(100), SERVERPROPERTY('Servername')) AS Server, msdb.dbo.backupset.database_name, msdb.dbo.backupset.backup_start_date, msdb.dbo.backupset.backup_finish_date, msdb.dbo.backupset.expiration_date, CASE msdb..backupset.type WHEN 'D' THEN 'Database' WHEN 'L' THEN 'Log' END AS backup_type, msdb.dbo.backupset.backup_size, msdb.dbo.backupmediafamily.logical_device_name, msdb.dbo.backupmediafamily.physical_device_name, msdb.dbo.backupset.name AS backupset_name, msdb.dbo.backupset.description FROM msdb.dbo.backupmediafamily INNER JOIN msdb.dbo.backupset ON msdb.dbo.backupmediafamily.media_set_id = msdb.dbo.backupset.media_set_id WHERE (CONVERT(datetime, msdb.dbo.backupset.backup_start_date, 102) >= GETDATE() - 2) ORDER BY msdb.dbo.backupset.database_name, msdb.dbo.backupset.backup_finish_date Comments Issue 17: To Drop existing snapshot and create a new snapshot . Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-May-10

G(0)

Description DROP DATABASE RFS_Delivery_Hybrid_Snapshot CREATE DATABASE RFS_Delivery_Hybrid_Snapshot ON (NAME='RollingForcast_delivery_Data',FILENAME='F:\SQL2K5DATA \RollingForcast_delivery.SPARSE') AS SNAPSHOT OF RFS_Delivery_Hybrid
CREATE DATABASE AdventureWorksDW2008_dbss9AM ON ( NAME = AdventureWorksDW2008_Data, FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Data \AdventureWorksDW2008_data_9AM.ss' ) AS SNAPSHOT OF AdventureWorksDW2008;

Comments

Page 9 of 211

Issue 18: EXECUTE ACCESS ON SP_OA Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-May-10 Query-Session Level

G(0)

Description SELECT 'GRANT EXECUTE ON '+NAME+' TO [MYHCL\BPRDB_BUDGET]' FROM SYSOBJECTS WHERE NAME LIKE '%SP_OA%' Comments Issue 19: To Find Missing Indexes Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-May-10 Indexing

G(0)

Description select db_name(d.database_id) dbname, object_name(d.object_id) tablename, d.index_handle, d.equality_columns, d.inequality_columns, d.included_columns, d.statement as fully_qualified_object, gs.* from sys.dm_db_missing_index_groups g join sys.dm_db_missing_index_group_stats gs on gs.group_handle = g.index_group_handle join sys.dm_db_missing_index_details d on g.index_handle = d.index_handle where d.database_id = d.database_id and d.object_id = d.object_id Comments

Page 10 of 211

Issue 20: Viewing the locking information Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-May-10 Blocking query

G(0)

Description select l.resource_type, l.resource_associated_entity_id ,object_name(sp.object_id) as objectname ,l.request_status,l.request_mode,request_session_id ,l.resource_description from sys.dm_tran_locks l left join sys.partitions sp on sp.hobt_id = l.resource_associated_entity_id where l.resource_database_id =db_id() Comments Issue 21: Viewing Blocking Information - sys.dm_tran_locks - sys.dm_os_waiting_tasks - sys.partitions Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-May-10 Blocking query

G(0)

Description select t1.resource_type, t1.resource_database_id, t1.resource_associated_entity_id, object_name(sp.object_id) as objectName, t1.request_mode, t1.request_session_id, t2.blocking_session_id from sys.dm_tran_locks as t1 join sys.dm_os_waiting_tasks as t2 on t1.lock_owner_address = t2.resource_address left join sys.partitions sp on sp.hobt_id = t1.resource_associated_entity_id Comments

Page 11 of 211

Issue 22: Building All Missing indexes in oneshot Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-May-10 Indexing

G(0)

Description SELECT 'CREATE NONCLUSTERED INDEX IX1_' + object_name(c.object_id) + left(cast(newid() as varchar(500)),5) + char(10) + ' on ' + c.statement + '(' + case when c.equality_columns is not null and c.inequality_columns is not null then c.equality_columns + ',' + c.inequality_columns when c.equality_columns is not null and c.inequality_columns is null then c.equality_columns when c.inequality_columns is not null then c.inequality_columns when c.equality_columns is null and c.inequality_columns is not null then c.inequality_columns end + ')' + char(10) + case when c.included_columns is not null then 'Include (' + c.included_columns + ')' else '' end as includes FROM sys.dm_db_missing_index_group_stats a inner join sys.dm_db_missing_index_groups b on a.group_handle = b.index_group_handle inner join sys.dm_db_missing_index_details c on c.index_handle = b.index_handle where db_name() = 'RMS1FEB_SAP' --and equality_columns is not null ORDER BY a.avg_total_user_cost * a.avg_user_impact * (a.user_seeks + a.user_scans)DESC Comments
Issue 23: sp_who2 -- sys.dm_exec_requests Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-May-10 Blocking query

G(0)

Description
sys.dm_exec_requests

Comments

Page 12 of 211

Issue 24: Retrieve Statements with the Lowest Plan Re-Use Counts Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-May-10 Performance Issue

G(0)

Description SELECT TOP 50 cp.cacheobjtype ,cp.usecounts ,size=cp.size_in_bytes ,stmt_start=qs.statement_start_offset ,stmt_end=qs.statement_end_offset ,qt.dbid ,qt.objectid ,qt.text ,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 statement ,qs.sql_handle ,qs.plan_handle FROM sys.dm_exec_query_stats qs cross apply sys.dm_exec_sql_text(qs.sql_handle) as qt inner join sys.dm_exec_cached_plans as cp on qs.plan_handle=cp.plan_handle where cp.plan_handle=qs.plan_handle and qt.dbid is NULL ORDER BY [usecounts],[statement] asc Comments

Page 13 of 211

Issue 25: Retrieve Statements with the Highest Plan Re-Use Counts Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-May-10 Performance Issue

G(0)

Description SELECT TOP 100 qs.sql_handle ,qs.plan_handle ,cp.cacheobjtype ,cp.usecounts ,cp.size_in_bytes ,qs.statement_start_offset ,qs.statement_end_offset ,qt.dbid ,qt.objectid ,qt.text ,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 statement FROM sys.dm_exec_query_stats qs cross apply sys.dm_exec_sql_text(qs.sql_handle) as qt inner join sys.dm_exec_cached_plans as cp on qs.plan_handle=cp.plan_handle where cp.plan_handle=qs.plan_handle --and qt.dbid = db_id() ORDER BY [dbid],[Usecounts] DESC Comments Issue 26: Determine CPU Resources Required for Optimization Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-May-10 Performance Issue

G(0)

Description Select * from sys.dm_exec_query_optimizer_info where counter in ('optimizations','elapsed time','trivial plan','tables','insert stmt','update stmt','delete stmt') Comments

Page 14 of 211

Issue 27: Retrieve Buffer Counts by Object and Index Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-May-10 Performance Issue

G(0)

Description use Northwind go select b.database_id, db=db_name(b.database_id) ,p.object_id ,object_name(p.object_id) as objname ,p.index_id ,buffer_count=count(*) from sys.allocation_units a, sys.dm_os_buffer_descriptors b, sys.partitions p where a.allocation_unit_id = b.allocation_unit_id and a.container_id = p.hobt_id and b.database_id = db_id() group by b.database_id,p.object_id, p.index_id order by buffer_count desc Comments Issue 28: Memory Usage- sys.dm_os_memory_clerks Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-May-10 Memory

G(0)

Description select name, type, sum(single_pages_kb + multi_pages_kb) as memoryUsedInKB from sys.dm_os_memory_clerks group by name,type order by SUM(Single_Pages_kb + multi_pages_KB) desc Comments

Page 15 of 211

Issue 29: Rebuild indexes in one shot per database wise Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-May-10

G(0)

Description use sapdb SET NOCOUNT ON; DECLARE @objectid int; DECLARE @indexid int; DECLARE @partitioncount bigint; DECLARE @schemaname sysname; DECLARE @objectname sysname; DECLARE @indexname sysname; DECLARE @partitionnum bigint; DECLARE @partitions bigint; DECLARE @frag float; DECLARE @command varchar(8000); -- ensure the temporary table does not exist IF EXISTS (SELECT name FROM sys.objects WHERE name = 'work_to_do') DROP TABLE work_to_do; -- conditionally select from the function, converting object and index IDs to names. SELECT object_id AS objectid, index_id AS indexid, partition_number AS partitionnum, avg_fragmentation_in_percent AS frag INTO work_to_do FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL , NULL, 'LIMITED') WHERE avg_fragmentation_in_percent > 10.0 AND index_id > 0; -- Declare the cursor for the list of partitions to be processed. DECLARE partitions CURSOR FOR SELECT * FROM work_to_do;
-- Open the cursor. OPEN partitions; -- Loop through the partitions. FETCH NEXT FROM partitions INTO @objectid, @indexid, @partitionnum, @frag; WHILE @@FETCH_STATUS = 0 BEGIN; SELECT @objectname = o.name, @schemaname = s.name FROM sys.objects AS o JOIN sys.schemas as s ON s.schema_id = o.schema_id WHERE o.object_id = @objectid; SELECT @indexname = name FROM sys.indexes WHERE object_id = @objectid AND index_id = @indexid; SELECT @partitioncount = count (*) FROM sys.partitions WHERE object_id = @objectid AND index_id = @indexid; -- 30 is an arbitrary decision point at which to switch between reorganizing and rebuilding

Page 16 of 211

IF @frag < 30.0 BEGIN; SELECT @command = 'ALTER INDEX ' + @indexname + ' ON ' + @schemaname + '.' + @objectname + ' REORGANIZE'; IF @partitioncount > 1 SELECT @command = @command + ' PARTITION=' + CONVERT (CHAR, @partitionnum); EXEC (@command); END; IF @frag >= 30.0 BEGIN; SELECT @command = 'ALTER INDEX ' + @indexname +' ON ' + @schemaname + '.' + @objectname + ' REBUILD'; IF @partitioncount > 1 SELECT @command = @command + ' PARTITION=' + CONVERT (CHAR, @partitionnum); EXEC (@command); END; PRINT 'Executed ' + @command; FETCH NEXT FROM partitions INTO @objectid, @indexid, @partitionnum, @frag; END; -- Close and deallocate the cursor. CLOSE partitions; DEALLOCATE partitions; -- drop the temporary table IF EXISTS (SELECT name FROM sys.objects WHERE name = 'work_to_do') DROP TABLE work_to_do; GO

Comments Issue 30: To Check product version - level -- Edition Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 28-May-10 28-May-10

G(0)

Description
SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')

Comments

Page 17 of 211

Issue 31: Checking All Memory Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 30-May-10

G(0)

Description
SELECT CONVERT (varchar(30), GETDATE(), 121) as runtime, DATEADD (ms, -1 * ((sys.cpu_ticks / sys.cpu_ticks_in_ms) - a.[Record Time]), GETDATE()) AS Notification_time, a.* , sys.ms_ticks AS [Current Time] FROM (SELECT x.value('(//Record/ResourceMonitor/Notification)[1]', 'varchar(30)') AS [Notification_type], x.value('(//Record/MemoryRecord/MemoryUtilization)[1]', 'bigint') AS [MemoryUtilization %], x.value('(//Record/MemoryRecord/TotalPhysicalMemory)[1]', 'bigint') AS [TotalPhysicalMemory_KB], x.value('(//Record/MemoryRecord/AvailablePhysicalMemory)[1]', 'bigint') AS [AvailablePhysicalMemory_KB], x.value('(//Record/MemoryRecord/TotalPageFile)[1]', 'bigint') AS [TotalPageFile_KB], x.value('(//Record/MemoryRecord/AvailablePageFile)[1]', 'bigint') AS [AvailablePageFile_KB], x.value('(//Record/MemoryRecord/TotalVirtualAddressSpace)[1]', 'bigint') AS [TotalVirtualAddressSpace_KB], x.value('(//Record/MemoryRecord/AvailableVirtualAddressSpace)[1]', 'bigint') AS [AvailableVirtualAddressSpace_KB], x.value('(//Record/MemoryNode/@id)[1]', 'bigint') AS [Node Id], x.value('(//Record/MemoryNode/ReservedMemory)[1]', 'bigint') AS [SQL_ReservedMemory_KB], x.value('(//Record/MemoryNode/CommittedMemory)[1]', 'bigint') AS [SQL_CommittedMemory_KB], x.value('(//Record/@id)[1]', 'bigint') AS [Record Id], x.value('(//Record/@type)[1]', 'varchar(30)') AS [Type], x.value('(//Record/ResourceMonitor/Indicators)[1]', 'bigint') AS [Indicators], x.value('(//Record/@time)[1]', 'bigint') AS [Record Time] FROM (SELECT CAST (record as xml) FROM sys.dm_os_ring_buffers WHERE ring_buffer_type = 'RING_BUFFER_RESOURCE_MONITOR') AS R(x)) a CROSS JOIN sys.dm_os_sys_info sys ORDER BY a.[Record Time] ASC

Comments Issue 32: Document - Mirroring Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 30-May-10 Mirroring

G(1)

Description Comments

Page 18 of 211

Issue 33: Document - Clustering - sql server 2005 Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 30-May-10 Cluster

G(1)

Description Comments

Issue 34: Document -- Network Connection Affinity Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 30-May-10 Cluster

G(1)

Description Comments

Issue 35: Document - Networker module for SQL Server 5.2 Installation Guide Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 30-May-10 Cluster

G(1)

Description Comments

Page 19 of 211

Issue 36: Document - Networker module for SQL Server 5.2 Administation Guide Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 30-May-10 Cluster

G(1)

Description Comments

Issue 37: Document - Upgrade Technical Resource Guide - Sql server 2005 Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 30-May-10

G(1)

Description

Comments Issue 38: Document - EMC Replicator Product Guide Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 30-May-10

G(2)

Description Comments

Page 20 of 211

Issue 39: Database consolidation [Step by Step] Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 30-May-10 Login_User_Schema

G(0)

Description

19 )Database consolidation [Step by Step]


Step 1: Create a blank new database which will contain all the objects of the databases we are going to consolidate.
CREATE DATABASE [ConsolidatedDatabaseName] ON (Name='', FileName='') LOG ON (Name='', FileName='')

Step 2: Create the users in this newly created database for the corresponding databases which are to be consolidated (before creating users, ensure that these logins are available on the server, if not then create the first).
CREATE LOGIN NewUserName WITH PASSWORD='', CHECK_POLICY=OFF,CHECK_EXPIRATION=OFF GO USE [ConsolidatedDatabaseName] GO CREATE USER [NewUserName] FOR LOGIN [NewUserName]

Step 3: Create the pre decided schemas for the corresponding databases which are to be consolidated in the new [ConsolidatedDatabase] and provide the authorization of these schemas to the corresponding users CREATE SCHEMA SchemaName AUTHORIZATION [NewUserName]. Step 4: Generate the script of the user tables of all the databases which will participate in consolidation. Step 5: In the generated script replace the schema name of the tables from <DBO> or < OldSchemaName> to <NewSchemaName>. Step 6: Run the script in order to create the tables with given schema names. Step 7: Similarly generate the script for Views, Functions & Stored Procedures and in script replace the <DBO> or < OldSchemaName> to <NewSchemaName>. Step 8: Run the script in order to create the Views, Functions & Stored Procedures with given schema names. Step 9: Grant Create Table, Create Procedure, Create View & Create Function permissions in the newly created database to all the corresponding users.
GRANT GRANT GRANT GRANT CREATE CREATE CREATE CREATE TABLE TO userName VIEW TO userName PROCEDURE TO userName FUNCTION TO userName

Step 10: Now import the data into the newly created tables from the live.
Comments

Page 21 of 211

Issue 40: Document - Server Consolidation Document Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 30-May-10

G(0)

Description Comments

Issue 41: Steps to Create a Two Node SQL Failover Cluster via the UI Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 31-May-10

G(1)

Description Comments

Issue 42: replication alert Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 16-Jun-10 Replication Concept

G(1)

Description Comments

Page 22 of 211

Issue 43: Rebuilding Non Clustered index Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 20-Jun-10 Indexing

G(0)

Description
DECLARE DBCURSOR CURSOR FOR SELECT NAME FROM SYS.DATABASES OPEN DBCURSOR; DECLARE @dbnames varchar(100), @sql nvarchar(4000); FETCH NEXT FROM DBCURSOR into @dbnames WHILE (@@FETCH_STATUS<>-1) BEGIN set @sql='USE '+@dbnames+';' PRINT 'REBULDING INDEXES ON DATABASE '+DB_NAME(DB_ID()); SET NOCOUNT ON; DECLARE @objectid int; DECLARE @indexid int; DECLARE @partitioncount bigint; DECLARE @schemaname sysname; DECLARE @objectname sysname; DECLARE @indexname sysname; DECLARE @partitionnum bigint; DECLARE @partitions bigint; DECLARE @frag float; DECLARE @command varchar(8000); -- ensure the temporary table does not exist IF EXISTS (SELECT name FROM sys.objects WHERE name = 'work_to_do') DROP TABLE work_to_do; -- conditionally select from the function, converting object and index IDs to names. SELECT object_id AS objectid, index_id AS indexid, partition_number AS partitionnum, avg_fragmentation_in_percent AS frag INTO work_to_do FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL , NULL, 'LIMITED') WHERE avg_fragmentation_in_percent > 10.0 AND index_id > 0 and index_type_desc='NONCLUSTERED INDEX'; -- Declare the cursor for the list of partitions to be processed. DECLARE partitions CURSOR FOR SELECT * FROM work_to_do; -- Open the cursor. OPEN partitions; -- Loop through the partitions. FETCH NEXT FROM partitions INTO @objectid, @indexid, @partitionnum, @frag; WHILE @@FETCH_STATUS = 0 BEGIN; SELECT @objectname = o.name, @schemaname = s.name FROM sys.objects AS o JOIN sys.schemas as s ON s.schema_id = o.schema_id

Page 23 of 211

WHERE o.object_id = @objectid; SELECT @indexname = name FROM sys.indexes WHERE object_id = @objectid AND index_id = @indexid; SELECT @partitioncount = count (*) FROM sys.partitions WHERE object_id = @objectid AND index_id = @indexid; -- 30 is an arbitrary decision point at which to switch between reorganizing and rebuilding IF @frag < 30.0 BEGIN; SELECT @command = 'ALTER INDEX ' + @indexname + ' ON ' + @schemaname + '.' + @objectname + ' REORGANIZE'; IF @partitioncount > 1 SELECT @command = @command + ' PARTITION=' + CONVERT (CHAR, @partitionnum); EXEC (@command); END; IF @frag >= 30.0 BEGIN; SELECT @command = 'ALTER INDEX ' + @indexname +' ON ' + @schemaname + '.' + @objectname + ' REBUILD'; IF @partitioncount > 1 SELECT @command = @command + ' PARTITION=' + CONVERT (CHAR, @partitionnum); EXEC (@command); END; PRINT 'Executed ' + @command; FETCH NEXT FROM partitions INTO @objectid, @indexid, @partitionnum, @frag; END; -- Close and deallocate the cursor. CLOSE partitions; DEALLOCATE partitions; --print @sql; exec (@sql); FETCH NEXT FROM DBCURSOR INTO @dbnames; end; CLOSE DBCURSOR; DEALLOCATE DBCURSOR; -- drop the temporary table --IF EXISTS (SELECT name FROM sys.objects WHERE name = 'work_to_do') -- DROP TABLE work_to_do; --GO

Comments

Page 24 of 211

Issue 44: msdtc fixes. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 21-Jun-10 Cluster

G(0)

Description

Some times Configuring MSDTC and their error can ruin your Windows Cluster service and your time as well. You may get one of the following error when you failover the MSDTC service from one Dedicated node to another. This would only happen if the Cluster services has been installed before installing and configuring MSDTC Service. Hence it is highly recommended that you first install and configure MSDTC and then configure the Windows Cluster Service.
Event ID: 4097 Description: MS DTC started with the following settings: Security Configuration (OFF = 0 and ON = 1): Network Administration of Transactions = 1, Network Clients = 0, Distributed Transactions using Native MSDTC Protocol = 1, Transaction Internet Protocol (TIP) = 0, XA Transactions = 1.

OR

Event ID: 4395 Description: MSDTC detected that MSDTC related information in the local registry is different from that in the shared cluster registry. Error Specifics: d:ntcomcom1xdtcsharedmtxclumtxclusetuphelper.cpp:541, CmdLine: C:WINNTSystem32msdtc.exe, Pid: 796 Data: 0000: 05 40 00 80 .@.?

OR

Event ID: 4384 Description: MS DTC was unable to start because the installation was not configured to run on a cluster. Please run comclust.exe and restart MS DTC. Error Specifics: d:ntcomcom1xdtcsharedmtxclumtxclusetuphelper.cpp:668, CmdLine: C:WINNTSystem32msdtc.exe, Pid: 796 OR Event ID : 7024 Source : Service Control Manager Description: The MSDTC service terminated with service specific error 3221229584.

Initially you should try and run the command below and check if it solves the problem:
msdtc -resetlog

If that does not help then follow the fix below: 1. Delete the DTC resource 2. Delete MSDTC folder from the quorum disk. On Node 1: Stop the Cluster Service Remove Enable network DTC Service with the command below:
msdtc -uninstall

Make sure to check the Success in the Event logs. Verify that the following registry key has been removed as well.. if not then remove it manually.
HKEY_CLASSES_ROOTCID HKEY_LOCAL_MACHINESOFTWAREMicrosoftMSDTC HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesMSDTC

Reboot the Server


Page 25 of 211

After the Server is back online reinstall Enable network DTC Service with the command below:
msdtc -install

Now create the DTC resource on Node 1 and it should come online. Now on Node 2 Stop the Cluster Services. Evict Node 2 from the Cluster Remove Enable network DTC Service with the command below:
msdtc -uninstall

Make sure to check the Success in the Event logs. Verify that the registry key has been removed as well.. if not then remove it manually. Reboot Reinstall Enable network DTC Service with the command below:
msdtc -install

Verify that the Service has now Started and also registry keys created. Rejoin the node back into the cluster.

Comments

Page 26 of 211

Issue 45: using uptime utility to Monitor Servers. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 23-Jun-10

G(0)

Description

Using the UPTIME Utility to Monitor Servers


The distinction between server administrator and database administrator often blurry. DBAs frequently need to track server uptime. This is particularly important where servers hosting poorly designed legacy applications require periodic reboots. To address this issue and to simply monitor server uptime statistics, we ve identified a quick and solution. The approach described below uses an executable available from Microsoft called uptime.exe. Uptime.exe is run from a command line and generates a single statement defining how long the system has been up and running. This information can be pulled into SQL Server for further processing.

Overview
Collecting the data is a very simple 3 step process: 1. Download the uptime.exe executable 2. Enable XP_CMDSHELL 3. Run a script that executes uptime.exe and capture the results Each of these steps is detailed below. Step 1. Download the uptime.exe executable: Uptime.exe is available http://support.microsoft.com/kb/232243. Download the file and copy it to the C:\WINDOWS\system32 on the SQL Server where you are collecting the uptime information. Note that this program does not need to be saved to every computer of interest, only the SQL Server that is aggregating the data. Uptime will be called from a SQL Script in step 3 below. Step 2. Enabling the XP_CMDSHELL Since we are going to be executing uptime.exe from SQL Scripts, you must ensure that XP_CMDSHELL is enabled for your server. To determine if it is already enabled, start a new query in SSMS and type SP_CONFIGURE. When you execute this command the system will identify what options are enabled. XP_CMDSHELL should have a 1 next to it if it is enabled. If it isn t enabled, it will have a zero next to it. I f XP_CM DSHELL i s not enabl ed i t can be done t hr ough SSM S. Connect t o each dat abase ser ver and execut e t he f ol l owi ng scr i pt - - To al l ow advanced opt i ons t o be changed. EXEC sp_conf i gur e ' show advanced opt i ons' , 1 GO - - To updat e t he cur r ent l y conf i gur ed val ue f or advanced opt i ons. RECONFI GURE GO - - To enabl e t he f eat ur e.
Page 27 of 211

EXEC sp_conf i gur e ' xp_cm dshel l ' , 1 GO - - To updat e t he cur r ent l y conf i gur ed val ue f or t hi s f eat ur e. RECONFI GURE GO Step 3. Collecting Data from uptime.exe Now that the application is installed and accessible, we can collect the data. The script below takes the output from the uptime application and inserts into a temporary table which is deleted after results are displayed. - - cr eat e t em por ar y ser ver upt i m e t abl e CREATE TABLE #t bl _upt i m e ( i d i nt i dent i t y ( 1, 1) , out _put var char ( m ax) ) - - execut e t he upt i m e. exe f i l e poi nt i ng i t at var i ous ser ver s I NSERT #t bl _upt i m e EXEC XP_CM DSHELL ' upt i m e \ \ SERVER A - - ser ver nam e her e I NSERT #t bl _upt i m e EXEC XP_CM DSHELL ' upt i m e \ \ SERVER B - - ser ver nam e her e ---m or e ser ver s can be added her e SELECT out _put AS ser ver _up_t i m e FROM #t bl _upt i m e W HERE out _put I S NOT NULL ORDER BY REPLACE( out _put , ' \ \ ' , ' ' ) ---m or e ser ver s her e DROP TABLE #t bl _upt i m e Note that a single copy of the uptime executable residing on the SQL Server can hit any number of other servers. The output from this simple script is below:
This raw output can be parsed using select statements or regular expressions to separate the data into columns. Similarly it can be fed into permanent tables and used to trigger various actions.

Discussion
There are a lot of advantages to using this approach for tracking your uptime. Uptime.exe is a free utility from Microsoft. It requires no installation and runs on both 32 and 64 bit operating systems. As you saw from the description above, implementation takes just a few minutes. Some don t like to enable XP_CMDSHELL for security reasons. Namely, once XP_CMDSHELL is enabled, some database users may be able execute commands against the operating system. Depending upon who is using your SQL Server, you may not want to allow that kind of access to your operating system environment.

Conclusion
Uptime.exe allows for a quick and easy way to track how long your servers have been running. This information can be used to track server uptime and to support the timely reboot of legacy systems that require it.
Comments

Page 28 of 211

Issue 46: How to change SQL Server parameters in a clustered environment when SQL Server is not online Category Status Priority Attachments (1) Category Active (1) High Assigned To Due Date Opened By Opened Date 23-Jun-10

G(0)

Description
---- http://support.microsoft.com/kb/953504

Comments

Issue 47: SQL Server technical bulletin - How to resolve a deadlock Category Status Priority Attachments (3) Category Active (1) High Assigned To Due Date Opened By Opened Date 23-Jun-10

G(0)

Description
---http://support.microsoft.com/kb/832524

Comments

Page 29 of 211

Issue 48: Shrink tempdb files Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 23-Jun-10

G(0)

Description
Use [Tempdb] GO SELECT name AS 'File Name' , physical_name AS 'Physical Name', size/128 AS 'Total Size in MB', size/128.0 - CAST(FILEPROPERTY(name, 'SpaceUsed') AS int)/128.0 AS 'Available Space In MB', * FROM sys.database_files;

tempdev O:\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\tempdb.mdf Total Size in MB: 15891 Available Size in MB: 15783.187500 templog O:\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\templog.ldf Total Size in MB: 259 Available Size in MB: 247.187500 select * from sys.dm_db_file_space_usage Unallocated_extent_page_count: 2020560 The unallocated extent page count when divided by 128 (number of pages in a mb) = 15785.625 mb Ive tried the following: USE [tempdb] GO DBCC SHRINKFILE (N'tempdev' , 1024) GO

USE [tempdb] GO DBCC SHRINKDATABASE (N'tempdb') GO

USE [tempdb] GO DBCC SHRINKFILE (N'tempdev' , 0, TRUNCATEONLY) GO

the shrink file gui window of tempdev shows allocated space of 8.00MB and available free space of -96.19mb ???? Can anyone help??

Page 30 of 211

Post #688222 GilaMonster Posted Wednesday, April 01, 2009 12:01 PM

SSCoach

Group: General Forum Members Last Login: Today @ 12:05 PM Points: 18,281, Visits: 13,345 Why do you need to shrink it? If it's grown that large it means that something within your production workload needs a 16 GB tempDB. If you do somehow force a shrink, it could well grow back to that size. Unless you are running out of disk space, there is no good reason to shrink the database. Empty space within won't cause issues. If your workload is such that tempDB needs to be that size, then make it that size from startup. Oh, and you may want to note that running Shrink on TempDB while it's in use can result in a corrupt tempDB. There is a kb article on that - http://support.microsoft.com/kb/307487

-------------------------------------------------------------------------------Gail Shaw

We walk in the dark places no others will enter We stand on the bridge and none may pass

Post #688249 sebastien piche Posted Wednesday, April 01, 2009 12:09 PM SSC Rookie

Group: General Forum Members Last Login: Today @ 7:42 AM Points: 28, Visits: 208 is not good idea shrink tempDB depend activity on your database but 16gb is not unusual my production server have 40Gb for tmpdb into 6 physical files. maybe considere add additional disk to have suffisent space. Post #688257 Mos-368173 Posted Thursday, April 02, 2009 3:30 AM Valued Member

Page 31 of 211

Group: General Forum Members Last Login: Monday, June 14, 2010 7:40 AM Points: 66, Visits: 163 I know that tempdb can get currupted and i have read the various Ms kb articles. I wouldnt be doing this during the day, but the transaction that caused the tempdb to grow so much was a one off and not our standard tempdb growth. i would be shrinking tempdev to around 10gb which is enough to handle our everyday transactions. I dont have the capacity to maintain a 16gb tempdb which is why i want to shrink it. The point is not why i am trying to do this but why it is not working when i try the options given by Microsoft Post #688653 GilaMonster Posted Thursday, April 02, 2009 3:51 AM

SSCoach

Group: General Forum Members Last Login: Today @ 12:05 PM Points: 18,281, Visits: 13,345 Did you run the 'update usage' that the kb article refered to?

-------------------------------------------------------------------------------Gail Shaw

We walk in the dark places no others will enter We stand on the bridge and none may pass

Post #688671 Cowboy DBA Posted Thursday, April 02, 2009 3:54 AM

Valued Member

Group: General Forum Members Last Login: Today @ 6:07 AM Points: 67, Visits: 1,029 We've had a similar issue on one of our environments. The only explanation I can give at the moment is similar to problems when attempting to shrink the transaction log file: if there is an active transaction at the end of the file then DBCC SHRINKFILE will not be able to shrink it. Like I allude to, this is only a guess. The script below should be able to tell you what pending I/O requests are on what particular database and file. That'll give you some idea regarding any (long/continuous) oustanding requests. Then maybe look at killing the

Page 32 of 211

spid which is causing the request which might enable you to shrink tempdb select database_id, file_id, io_stall, io_pending_ms_ticks, scheduler_address from sys.dm_io_virtual_file_stats(NULL, NULL)t1, sys.dm_io_pending_io_requests as t2 where t1.file_handle = t2.io_handle The above advice might be a load of rubbish but definitely comes without warranty and I take no responsibility for bringing your company down to a grinding halt. Post #688676 Mos-368173 Posted Thursday, April 02, 2009 3:59 AM Valued Member

Group: General Forum Members Last Login: Monday, June 14, 2010 7:40 AM Points: 66, Visits: 163 Hi, I ran updateusage against tempdb and it didnt resolve the minus free space issue. Im a bit baffled about it all - a friend mentioned that it may be because the tempdev is holding data at the back of the file preventing a shrink (similar to the way a log would) but a reorganise would have resolved this. Is there any way to check this out? Post #688678 Boolean_z Posted Thursday, April 02, 2009 4:24 AM Valued Member

Group: General Forum Members Last Login: Thursday, February 18, 2010 11:36 AM Points: 63, Visits: 119 GUI showing percent free in minus is common for large tempdb's, I dont know exactly why is this, but I have seem in several servers. Post #688701 SUBRAHMANYA HEDGE Posted Thursday, April 02, 2009 4:26 AM SSC Veteran

Page 33 of 211

Group: General Forum Members Last Login: Wednesday, June 02, 2010 10:15 PM Points: 201, Visits: 187 Can you try this? It worked for me... USE [tempdb] GO Checkpoint DBCC SHRINKFILE (N'tempdev' , 0, TRUNCATEONLY) GO Post #688703 Cowboy DBA Posted Thursday, April 02, 2009 4:27 AM

Valued Member

Group: General Forum Members Last Login: Today @ 6:07 AM Points: 67, Visits: 1,029 Or use tempdb backup log tempdb WITH NO_LOG dbcc shrinkfile (templog,0) dbcc shrinkfile (tempdev,0) Post #688706

Prev Topic | Next Topic

14 posts, Page 1 of 212 Permissions

Comments

Page 34 of 211

Issue 49: A transaction log grows unexpectedly or becomes full on a computer that is running SQL Server Category Status Priority Attachments (3) Category Active (1) High Assigned To Due Date Opened By Opened Date 24-Jun-10 Corruption

G(1)

Description Comments [Version: 6/24/2010 10:54:52 AM ] http://support.microsoft.com/kb/317375

Issue 50: Viewing tempdb Size and Growth Parameters-Autogrowth/on off Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 26-Jun-10

G(0)

Description SELECT name AS FileName, size*1.0/128 AS FileSizeinMB, CASE max_size WHEN 0 THEN 'Autogrowth is off.' WHEN -1 THEN 'Autogrowth is on.' ELSE 'Log file will grow to a maximum size of 2 TB.' END, growth AS 'GrowthValue', 'GrowthIncrement' = CASE WHEN growth = 0 THEN 'Size is fixed and will not grow.' WHEN growth > 0 AND is_percent_growth = 0 THEN 'Growth value is in 8-KB pages.' ELSE 'Growth value is a percentage.' END FROM tempdb.sys.database_files; GO Comments

Page 35 of 211

Issue 51: How to create databases or change disk file locations on a shared cluster drive on which SQL Server was not originally installed Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 01-Jul-10

G(1)

Description

1. Open the Cluster Administrator. 2. Make sure that all the physical disk resources that contain SQL Server databases are in the same group as the SQL Server resource. 3. Right-click the SQL Server resource, and then bring the resource into an Offline state by clicking Bring Offline. 4. Right-click the SQL Server resource, and then click Properties. 5. Click the Dependencies tab. 6. Click Modify to add the disk to the dependencies list for that resource. 7. Bring the SQL Server resource back online, and then put the SQL Server files on that shared cluster disk.
Comments

Page 36 of 211

Issue 52: Change the IP addresses of SQL Server 2000 failover cluster instances Category Status Priority Attachments (1) Category Active (1) High Assigned To Due Date Opened By Opened Date 01-Jul-10

G(0)

Description

If you must change the IP address of your existing SQL Server 2000 failover cluster instance, whether it is a default instance or a named instance, you can use the Advanced\Maintain Virtual Server for Failover Clustering option in the SQL Server 2000 Setup program. To use the Advanced\Maintain Virtual Server for Failover Clustering option, follow these steps: 1. Insert the SQL Server 2000 Enterprise Edition CD, and then click SQL Server 2000 Components. 2. Click Install Database Server. 3. On the Welcome screen, click Next. 4. Type the name of the failover cluster instance that you want to modify, and then click Next. 5. Click the Advanced options tab, and then click Next. 6. Click Maintain a Virtual Server for Failover Clustering, and then click Next. 7. In the Failover Clustering dialog box, you can: Add an IP address for additional networks. Remove and replace an existing IP address. Remove IP addresses that you do not need. 1. After you make these changes, click Add, and then click Next. 2. 3. Note Assign only one IP address for each network and one network for each network adapter. SQL Server requires that each IP address that is assigned to it have its own unique subnet mask. SQL Server does not support multiple IP addresses on the same subnet because this may result in duplicated names on the network. For example, if you have a public network and a private network and you want to assign an additional IP address to your SQL Server failover cluster instance, you must add another network adapter to each node to create a new network. You can then assign the additional IP address to the new network. 1. Make any changes to the nodes, and then click Next. 2. Verify the requested user information and password, and then click Next. 3. 4. To verify that the changes were made, see the SQL Server 2000 IP resource properties in Cluster Administrator for the failover cluster instance. 5. Click Finish.

Comments

Page 37 of 211

Issue 53: Change the IP address of SQL Server 2005 failover cluster instances Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 01-Jul-10

G(0)

Description

To change the IP address on any Microsoft SQL Server 2005 failover cluster instance, follow these steps: Warning The computer that is running SQL Server will be offline during this process. Take the SQL Server IP Address resource offline. Check Configuration Manager for an alias that matches the Virtual SQL Server name. To do this, follow these steps: Click Start, point to All Programs, point to Microsoft SQL Server 2005, point to Configuration Tools, and then click SQL Server Configuration Manager. Expand SQL Native Client Configuration, and then click Aliases. If an alias exists whose name is the same as the SQL Server Virtual Server name, change the IP address of the alias to a new IP address. Right-click SQL Server IP Address resource, and then click Properties. Click the Parameters tab. Enlist the new IP address. Click Apply, and then click OK. Bring the IP Address resource online to validate no conflicts. Right-click the SQL Server Failover Cluster Instances group name, and then click Bring Online. Open the current SQL Server errorlog file, and verify that the new IP Address is used. Warning SQL Mail is not fully supported when it is used with SQL Server 2000 failover clustering because MAPI is not cluster-aware. When SQL Mail is used on a failover cluster, Microsoft makes commercially reasonable efforts to provide support but cannot guarantee stability or availability. Microsoft has confirmed that this is a problem in SQL Server 6.5, 7.0, and 2000 when SQL Mail is used on a failover cluster. If the SQL Server 2005 or the SQL Server 2008 clustered instance is already installed, you have to add a new virtual IP address on which SQL Server 2005 or SQL Server 2008 will listen. To do this, follow these steps: Click Start, click Run, type cluadmin, and then click OK. In the Cluster Administrator window, expand the Groups node. Expand the group to which you want to add the IP address resource. Bring the SQL network name resource offline. Create a new IP address resource. Note The new IP address is the additional virtual IP address on which SQL Server 2005 will listen. To do this, follow these steps: Right-click the group, point to New, and then click Resource. In the New Resource dialog box, type the name that you want to use for the
Page 38 of 211

resource, select IP Address in the Resource type list, and then click Next. In the TCP/IP Address Parameters dialog box, specify the IP address, and then click Finish. Configure the SQL network name resource to be dependent on the new IP address. To do this, follow these steps: Right-click the SQL network name resource, and then click Properties. In the Properties dialog box, click the Dependencies tab. On the Dependencies tab, click Modify. Add the new IP address from the Available resources list to the Resource dependencies list. Click OK two times. Bring all resources online.

Comments

Page 39 of 211

Issue 54: Moving the master Database Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 01-Jul-10

G(0)

Description

To move the master database, follow these steps. 1. From the Start menu, point to All Programs, point to Microsoft SQL Server, point to Configuration Tools, and then click SQL Server Configuration Manager. 2. In the SQL Server Services node, right-click the instance of SQL Server (for example, SQL Server (MSSQLSERVER)) and choose Properties. 3. In the SQL Server (instance_name) Properties dialog box, click the Advanced tab. 4. Edit the Startup Parameters values to point to the planned location for the master database data and log files, and click OK. Moving the error log file is optional. 1. The parameter value for the data file must follow the -d parameter and the value for the log file must follow the -l parameter. The following example shows the parameter values for the default location of the master data and log files. 2. 3. Copy
4. -dC:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER \MSSQL\DATA\ 5. master.mdf;-eC:\Program Files\Microsoft SQL Server\MSSQL10_ 50.MSSQLSERVER\MSSQL\ 6. LOG\ERRORLOG;-lC:\Program Files\Microsoft SQL Server\MSSQL10_ 50.MSSQLSERVER\MSSQL\ 7. DATA\mastlog.ldf

8. If the planned relocation for the master data and log files is E:\SQLData, the parameter values would be changed as follows: 9. 10. Copy

11. -dE:\SQLData\master.mdf;-eC:\Program Files\Microsoft SQL Server \MSSQL10_50.MSSQLSERVER\MSSQL\LOG\ERRORLOG;-lE:\SQLData\mastlog.ldf

5. Stop the instance of SQL Server by right-clicking the instance name and choosing Stop. 6. Move the master.mdf and mastlog.ldf files to the new location. 7. Restart the instance of SQL Server. 8. Verify the file change for the master database by running the following query. 1. 2. Copy
3. 4. 5. 6. SELECT name, physical_name AS CurrentLocation, state_desc FROM sys.master_files WHERE database_id = DB_ID('master'); GO

Comments

Page 40 of 211

Issue 55: Moving the tempdb database Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 01-Jul-10

G(0)

Description

Because tempdb is re-created each time the instance of SQL Server is started, you do not have to physically move the data and log files. The files are created in the new location when the service is restarted in step 3. Until the service is restarted, tempdb continues to use the data and log files in existing location. 1. Determine the logical file names of the tempdb database and their current location on the disk.
1. 2. 3. 4. SELECT name, physical_name AS CurrentLocation FROM sys.master_files WHERE database_id = DB_ID(N'tempdb'); GO

1. Change the location of each file by using ALTER DATABASE. 1. 2. Copy

3. USE master; 4. GO 5. ALTER DATABASE tempdb 6. MODIFY FILE (NAME = tempdev, FILENAME = 'E:\SQLData\tempdb.mdf'); 7. GO 8. ALTER DATABASE tempdb 9. MODIFY FILE (NAME = templog, FILENAME = 'F:\SQLLog\templog.ldf'); 10. GO

2. Stop and restart the instance of SQL Server. 3. Verify the file change. 1. 2. Copy

3. SELECT name, physical_name AS CurrentLocation, state_desc 4. FROM sys.master_files 5. WHERE database_id = DB_ID(N'tempdb');

4. Delete the tempdb.mdf and templog.ldf files from the original location.
Comments

Page 41 of 211

Issue 56: NET START MSSQLSERVER /f /T3608 Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 01-Jul-10 Corruption

G(0)

Description

Start the instance of SQL Server in master-only recovery mode by entering one of the following commands at the command prompt. The parameters specified in these commands are case sensitive. The commands fail when the parameters are not specified as shown. For the default (MSSQLSERVER) instance, run the following command:
NET START MSSQLSERVER /f /T3608 1222 NET START MSSQLSERVER /f/m/c /T3608 NET START MSSQLSERVER /f/m"SQLCMD"/c /T3608

Comments

Page 42 of 211

Issue 57: Some Important tables/Procedure associated with Replication. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 02-Jul-10 Replication Concept

G(0)

Description

MSrepl_commands -- The entries in the MSrepl_commands table are commands indicating the location of .sch and .bcp files, any other snapshot files, and references to any pre- or post-snapshot scripts. Msrepl_Transactions-The entries in the MSrepl_transactions table are commands relevant to synchronizing the Subscriber sp_replcmd -- Returns the commands for transactions marked for replication. This stored procedure is executed at the Publisher on the publication database. sp_replcmds is used by the log reader process in transactional replication. Replication treats the first client that runs sp_replcmds within a given database as the log reader. This procedure can generate commands for owner-qualified tables or not qualify the table name (the default). Adding qualified table names allows replication of data from tables owned by a specific user in one database to tables owned by the same user in another database. Because the table name in the source database is qualified by the owner name, the owner of the table in the target database must be the same owner name. Clients who attempt to run sp_replcmds within the same database receive error 18752 until the first client disconnects. After the first client disconnects, another client can run sp_replcmds, and becomes the new log reader. A warning message number 18759 is added to both the Microsoft SQL Server error log and the Microsoft Windows application log if sp_replcmds is unable to replicate a text command because the text pointer was not retrieved in the same transaction. sp_repldone : sp_repldone is used in transactional replication. sp_repldone is used by the log reader process to track which transactions have been distributed. With sp_repldone, you can manually tell the server that a transaction has been replicated (sent to the Distributor). It also allows you to change the transaction marked as the next one awaiting replication. You can move forward or backward in the list of replicated transactions. (All transactions less than or equal to that transaction are marked as distributed.) The required parameters xactid and xact_seqno can be obtained by using sp_repltrans or sp_replcmds. When xactid is NULL, xact_seqno is NULL, and reset is 1, all replicated transactions in the log are marked as distributed. This is useful when there are replicated transactions in the transaction log that are no longer valid and you want to truncate the log, for example:
EXEC sp_repldone @xactid = NULL, @xact_segno = NULL, @numtrans = 0, @time = 0, @reset = 1

Page 43 of 211

sp_refreshsubscriptions : Add subscriptions to new articles in a pull subscription for all the existing Subscribers to the publication. This stored procedure is executed at the Publisher on the publication database.

Comments
Issue 58: How Snapshot Replication Works Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 02-Jul-10 Replication Concept

G(0)

Description

A)By default, all three types of replication use a snapshot to initialize Subscribers. B)The SQL Server Snapshot Agent always generates the snapshot files, but the agent that delivers the files differs depending on the type of replication being used. C)Snapshot replication and transactional replication use the Distribution Agent to deliver the files, whereas merge replication uses the SQL Server Merge Agent. D)The Snapshot Agent runs at the Distributor. E) The Distribution Agent and Merge Agent run at the Distributor for push subscriptions, or at Subscribers for pull subscriptions. E)For more information about push and pull subscriptions, see Subscribing to Publications. For more information about agents, see Replication Agents Overview. F)Snapshots can be generated and applied either immediately after the subscription is created or according to a schedule set at the time the publication is created. G)The Snapshot Agent prepares snapshot files containing the schema and data of published tables and database objects, stores the files in the snapshot folder for the Publisher, and records tracking information in the distribution database on the Distributor. H)You specify a default snapshot folder when you configure a Distributor, but you can specify an alternate location for a publication instead of or in addition to the default. I)For more information, see Alternate Snapshot Folder Locations. Note

Comments

Page 44 of 211

Issue 59: How to Add a fresh Subscriber with Few articles only --- Very Very Good. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 04-Jul-10 Replication Concept

G(0)

Description exec sp_addsubscription @publication = N'adv', @subscriber = N'rkumar33', @destination_db = N'adv_2', @subscription_type = N'Push', @sync_type = N'automatic', @article = N'Frag', @update_mode = N'read only', @subscriber_type = 0, @reserved='Internal'

exec sp_addpushsubscription_agent @publication = N'adv', @subscriber = N'rkumar33', @subscriber_db = N'adv_2', @job_login = null, @job_password = null, @subscriber_security_mode = 0, @subscriber_login = N'sa', @subscriber_password = punam@123, @frequency_type = 64, @frequency_interval = 0, @frequency_relative_interval = 0, @frequency_recurrence_factor = 0, @frequency_subday = 0, @frequency_subday_interval = 0, @active_start_time_of_day = 0, @active_end_time_of_day = 235959, @active_start_date = 20100704, @active_end_date = 99991231, @enabled_for_syncmgr = N'False', @dts_package_location = N'Distributor' GO

Comments

Page 45 of 211

Issue 60: How to Add a Article without generating new snapshot. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 04-Jul-10 Replication Concept

G(0)

Description

Friday, January 30, 2009


SQL 2005 Transaction Replication Adding new article to an existing publication
I have an existing publication with 10 articles configured for Transactional replication. The replication is running fine. Now I wish to add another table (article) to this publication. My requirement is to ensure that I dont need to generate a snapshot of all the articles being published, if I add a single article only that particular article should be published. Thanks to Hilary Cotter and Paul Ibison, fellow SQL Server MVPs. Following their advice i managed to accomplish this. I added the single article using the below command, use mydb go sp_addarticle @publication='mypublication', @article='dbo.test,@source_table='test' go I got the following error for the above command, Msg 20607, Level 16, State 1, Procedure sp_MSreinit_article, Line 99 Cannot make the change because a snapshot is already generated. Set @force_invalidate_snapshot to 1 to force the change and invalidate the existing snapshot. The reason behind this error message was that there was already a snapshot that was created recently. Since I added a new article it wouldnt be able to use the existing snapshot so I need to use the option @force_invalidate_snapshot=1 to invalidate the existing snapshot and it would generate a new snapshot to be applied to the subscriber. use mydb go sp_addarticle @publication='mypublication', @article='dbo.test,@source_table='test' , @force_invalidate_snapshot=1 go Now I ran Exec sp_helppublication in my publication database and checked the following fields, 1. Immediate_sync 2. Allow_anonymous

Page 46 of 211

Both the fields were set to ON as they showed a value 1 which is enabled. If the Immediate_sync is enabled, everytime you add a new article it will cause the entire snapshot to be applied and not the one for the particular article alone. Usually, the immediate_sync publication property is set to true if we allowed anonymous subscriptions while creating the publication through the CreatePublication wizard. To prevent the complete snapshot, run the script below, EXEC sp_changepublication @publication = 'mypublication', @property = N'allow_anonymous', @value = 'false' GO EXEC sp_changepublication @publication = 'mypublication', @property = N'immediate_sync', @value = 'false' GO Now I adding the subscription to the existing publisher for the single table alone using the below command, EXEC sp_addsubscription @publication = ''mypublication'', @article = 'dbo.test', @subscriber = 'Subscriberservername', @destination_db = 'mydestinationdbname' I got the following error message while running the above command in my publication database. Specify all articles when subscribing to a publication using concurrent snapshot processing This error occurs when the existing publication was set up with concurrent snapshot option and means that you can't synchronize subscriptions for such publications without a complete resynchronization. There are 2 workarounds: (a) By specifying @reserve = 'internal' when you add the subscription for the new article and the snapshot agent should generate snapshot for the new article after that and b.) Changing the sync_method from 'concurrent' to either 'database snapshot' (enterprise edition only in SQL Server 2005) or 'native' (which locks table during snapshot generation). Change the sync_method will force a reinitialization of all your subscriptions at this point. Alternatively you could create another publication and use this instead. I ran this command and it worked fine, EXEC sp_addsubscription @publication = ''mypublication'', @article = 'dbo.test', @subscriber = 'Subscriberservername', @destination_db = 'mydestinationdbname', @reserved='Internal' Now I went ahead and started the snapshot agent in publisher, it worked perfectly. I can now
Page 47 of 211

see that only the particular table I added was replicated. So from now on to apply the snapshots of the entire articles we need to reinitialize the subscriptions since the immediate_sync is set to off.
Comments [Version: 7/4/2010 4:11:20 PM ] -- http://deepakrangarajan.blogspot.com/2009/01/sql-2005-transactionreplication-adding.html--

Page 48 of 211

Issue 61: Codeing Guidelines -- Transaction related. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 05-Jul-10

G(0)

Description

It is important to keep transactions as short as possible. When a transaction is started, a database management system (DBMS) must hold many resources until the end of the transaction to protect the atomicity, consistency, isolation, and durability (ACID) properties of the transaction. If data is modified, the modified rows must be protected with exclusive locks that prevent any other transaction from reading the rows, and exclusive locks must be held until the transaction is committed or rolled back. Depending on transaction isolation level settings, SELECT statements may acquire locks that must be held until the transaction is committed or rolled back. Especially in systems with many users, transactions must be kept as short as possible to reduce locking contention for resources between concurrent connections. Longrunning, inefficient transactions may not be a problem with small numbers of users, but they are intolerable in a system with thousands of users.

Coding Guidelines
These are guidelines for coding efficient transactions: Do not require input from users during a transaction. Get all required input from users before a transaction is started. If additional user input is required during a transaction, roll back the current transaction and restart the transaction after the user input is supplied. Even if users respond immediately, human reaction times are vastly slower than computer speeds. All resources held by the transaction are held for an extremely long time, which has the potential to cause blocking problems. If users do not respond, the transaction remains active, locking critical resources until they respond, which may not happen for several minutes or even hours. Do not open a transaction while browsing through data, if at all possible. Transactions should not be started until all preliminary data analysis has been completed. Keep the transaction as short as possible. After you know the modifications that have to be made, start a transaction, execute the modification statements, and then immediately commit or roll back. Do not open the transaction before it is required. To reduce blocking, consider using a row versioning-based isolation level for read-only queries. For more information, see Using Row Versioning-based Isolation Levels. Make intelligent use of lower transaction isolation levels.
Page 49 of 211

Many applications can be readily coded to use a read-committed transaction isolation level. Not all transactions require the serializable transaction isolation level. Make intelligent use of lower cursor concurrency options, such as optimistic concurrency options. In a system with a low probability of concurrent updates, the overhead of dealing with an occasional "somebody else changed your data after you read it" error can be much lower than the overhead of always locking rows as they are read. Access the least amount of data possible while in a transaction. This lessens the number of locked rows, thereby reducing contention between transactions.

Avoiding Concurrency and Resource Problems


To prevent concurrency and resource problems, manage implicit transactions carefully. When using implicit transactions, the next Transact-SQL statement after COMMIT or ROLLBACK automatically starts a new transaction. This can cause a new transaction to be opened while the application browses through data, or even when it requires input from the user. After completing the last transaction required to protect data modifications, turn off implicit transactions until a transaction is once again required to protect data modifications. This process lets the SQL Server Database Engine use autocommit mode while the application is browsing data and getting input from the user. In addition, when the snapshot isolation level is enabled, although a new transaction will not hold locks, a long-running transaction will prevent the old versions from being removed from tempdb.
Comments Issue 62: Trouble Shoot Performance Problem. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 05-Jul-10

G(1)

Description Comments

Page 50 of 211

Issue 63: Database Mirroring Document. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 05-Jul-10 Mirroring

G(1)

Description Comments

Issue 64: Database Corruption & Recovery -- Very Very Good Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 05-Jul-10 Corruption

G(1)

Description Comments

Issue 65: Installing sql server 2008 on windows server 2008 cluster Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 07-Jul-10 Cluster

G(0)

Description Comments [Version: 7/7/2010 5:50:35 PM ] http://www.mssqltips.com/tip.asp?tip=1698

Page 51 of 211

Issue 66: Transaction Related Dynamic Management Views and Functions (Transact-SQL)-sys.dm_tran_active_snapshot_databse_transactions Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 08-Jul-10

G(0)

Description

sys.dm_tran_active_snapshot_database_transactions (Transact-SQL) -sys.dm_tran_active_snapshot_database_transactions (Transact-SQL) In a SQL Server instance, this dynamic management view returns a virtual table for all active transactions that generate or potentially access row versions. Transactions are included for one or more of the following conditions: When either or both ALLOW_SNAPSHOT_ISOLATION and READ_COMMITTED_SNAPSHOT database options are set to ON: There is one row for each transaction that is running under snapshot isolation level, or read-committed isolation level that is using row versioning. There is one row for each transaction that causes a row version to be created in the current database. For example, the transaction generates a row version by updating or deleting a row in the current database. When a trigger is fired, there is one row for the transaction under which the trigger is executing. When an online indexing procedure is running, there is one row for the transaction that is creating the index. When Multiple Active Results Sets (MARS) session is enabled, there is one row for each transaction that is accessing row versions.

Comments Issue 67: Incomplete transaction may hold large number of locks and cause blocking Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 08-Jul-10

G(1)

Description Comments

Page 52 of 211

Issue 68: Incomplete transaction may hold large number of locks and cause blocking Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 08-Jul-10

G(1)

Description Comments

Issue 69: Sql server setup cluster text files Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 08-Jul-10 Cluster

G(1)

Description Comments

Issue 71: Find Filegroups with Full-text indexes in them Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 09-Jul-10

G(0)

Description SELECT DISTINCT Name FROM sys.filegroups f INNER JOIN sys.fulltext_indexes i ON f.data_space_id = i.data_space_id GO Comments

Page 53 of 211

Issue 72: SQL code for the partitoned example Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 09-Jul-10

G(0)

Description USE AdventureWorks2008;


-- Create the partition function CREATE PARTITION FUNCTION [OrderDateRangePFN](datetime) AS RANGE RIGHT FOR VALUES (N'2001-01-01 00:00:00', N'2002-01-01 00:00:00', N'2003-01-01 00:00:00', N'2004-01-01 00:00:00'); -- Create the partition scheme CREATE PARTITION SCHEME [OrderDatePScheme] AS PARTITION [OrderDateRangePFN] TO ([Primary], [Primary], [Primary], [Primary], [Primary]); -- Create two tables: SalesOrderHeader is the partitioned table and SalesOrderHeaderOLD is the non-partitioned table CREATE TABLE [dbo].[SalesOrderHeader] ( [SalesOrderID] [int] NULL, [RevisionNumber] [tinyint] NOT NULL, [OrderDate] [datetime] NOT NULL, [DueDate] [datetime] NOT NULL, [ShipDate] [datetime] NULL, [Status] [tinyint] NOT NULL ) ON [OrderDatePScheme]([OrderDate]); CREATE TABLE [dbo].[SalesOrderHeaderOLD]( [SalesOrderID] [int] NULL, [RevisionNumber] [tinyint] NOT NULL, [OrderDate] [datetime] NOT NULL , [DueDate] [datetime] NOT NULL, [ShipDate] [datetime] NULL, [Status] [tinyint] NOT NULL); -- Load data into the partitioned table INSERT INTO SalesOrderHeader SELECT [SalesOrderID],[RevisionNumber], [OrderDate],[DueDate],[ShipDate],[Status] FROM SALES.[SalesOrderHeader]; CREATE CLUSTERED INDEX SalesOrderHeaderCLInd ON SalesOrderHeader(OrderDate) ON OrderDatePScheme(OrderDate); CREATE CLUSTERED INDEX SalesOrderHeaderOLDCLInd ON SalesOrderHeaderOLD(OrderDate); ALTER TABLE [DBO].[SalesOrderHeaderOLD] WITH CHECK ADD CONSTRAINT [CK_SalesOrderHeaderOLD_ORDERDATE] CHECK ([ORDERDATE]>=('2003-01-01 00:00:00') AND [ORDERDATE]<('2004-01-01 00:00:00')); -- Verify data in the partitioned table SELECT $partition.OrderDateRangePFN(OrderDate) AS 'Partition Number' ,min(OrderDate) AS 'Min Order Date' , max(OrderDate) AS 'Max Order
Page 54 of 211

Date',count(*) AS 'Rows In Partition' FROM SalesOrderHeader GROUP BY $partition.OrderDateRangePFN(OrderDate); -- Switch the data from partition 4 into the SalesOrderHeaderOLD table ALTER TABLE SalesOrderHeader SWITCH PARTITION 4 TO SalesOrderHeaderOLD; -- Switch the data from SalesOrderHeaderOLD back to partition 4 ALTER TABLE SalesOrderHeaderOLD SWITCH TO SalesOrderHeader PARTITION 4; --To merge a partition range ALTER PARTITION FUNCTION OrderDateRangePFN() MERGE RANGE ('2003-01-01 00:00:00'); -- To split a partition range ALTER PARTITION SCHEME OrderDatePScheme NEXT USED [Primary]; ALTER PARTITION FUNCTION OrderDateRangePFN() SPLIT RANGE ('2003-01-01 00:00:00');

Comments
Issue 73: Document -- Failover cluster resource dependentices in sql server Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 09-Jul-10

G(1)

Description Comments

Issue 74: 70-443_Designing_a_Database_Server_Infrastructure_Using_MS_SQL_Server_2005_-_Unlocked Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 12-Jul-10

G(1)

Description Comments

Page 55 of 211

Issue 75: Setup for Microsoft Cluster Services in VMWare. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 12-Jul-10

G(1)

Description Comments

Issue 76: Document Hyper-V_Using hyper-V anf Failover Cluster Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 12-Jul-10

G(1)

Description Comments

Issue 77: Running Profiler in sql server 2000. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 13-Jul-10

G(1)

Description Comments

Page 56 of 211

Issue 78: ITSM Essentials -Presentation v1.0 Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 13-Jul-10

G(1)

Description Comments

Issue 79: Very Very Good Link it has multiple Link. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 14-Jul-10

G(0)

Description
http://msdn.microsoft.com/en-us/library/ee229552(v=SQL.10).aspx

Comments [Version: 7/14/2010 6:44:34 PM ] http://msdn.microsoft.com/en-us/library/ee229552(v=SQL.10).aspx Issue 80: document -- Whats New in sql server Agent. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 14-Jul-10

G(1)

Description
http://msdn.microsoft.com/en-us/library/ee229552(v=SQL.10).aspx

Comments [Version: 7/14/2010 6:48:29 PM ] http://msdn.microsoft.com/en-us/library/ee229552(v=SQL.10).aspx

Page 57 of 211

Issue 81: Document - PieceMeal restore Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 14-Jul-10

G(1)

Description Comments

Issue 82: Calculating the value of proposed indexes Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 15-Jul-10 Indexing

G(0)

Description
select * from ( select user_seeks * avg_total_user_cost * (avg_user_impact * 0.01) as index_advantage, migs.* from sys.dm_db_missing_index_group_stats migs) as migs_adv inner join sys.dm_db_missing_index_groups as mig

Comments

Page 58 of 211

Issue 83: Finding Server Name -- Instance Name -- Hostname -- port Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 21-Aug-10

G(0)

Description set nocount on


Declare @key Varchar(100), @PortNumber varchar(20) if charindex('\',CONVERT(char(20), SERVERPROPERTY('servername')),0) <>0 begin set @key = 'SOFTWARE\MICROSOFT\Microsoft SQL Server \'+@@servicename+'\MSSQLServer\Supersocketnetlib\TCP' end else begin set @key = 'SOFTWARE\MICROSOFT\MSSQLServer\MSSQLServer\Supersocketnetlib \TCP' end EXEC master..xp_regread @rootkey='HKEY_LOCAL_MACHINE', @key=@key, @value_name='Tcpport',@value=@PortNumber OUTPUT SELECT CONVERT(char(20), SERVERPROPERTY('servername')) ServerName, CONVERT(char(20), SERVERPROPERTY('InstanceName')) instancename, CONVERT(char(20), SERVERPROPERTY('MachineName')) as HOSTNAME, convert(varchar(10),@PortNumber) PortNumber

Comments

Page 59 of 211

Issue 84: sp_scriptpublicationcustomprocs 'ecprdpub' Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-Sep-10 Replication Concept

G(0)

Description
to generate an script of custom proc

Comments

Issue 85: Providing batch-execution statistics Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 29-Sep-10 Indexing

G(0)

Description SELECT s2.dbid, s1.sql_handle, (SELECT TOP 1 SUBSTRING(s2.text,statement_start_offset / 2+1 , ( (CASE WHEN statement_end_offset = -1 THEN (LEN(CONVERT(nvarchar(max),s2.text)) * 2) ELSE statement_end_offset END) - statement_start_offset) / 2+1)) AS sql_statement, execution_count, plan_generation_num, last_execution_time, total_worker_time, last_worker_time, min_worker_time, max_worker_time, total_physical_reads, last_physical_reads, min_physical_reads, max_physical_reads, total_logical_writes, last_logical_writes, min_logical_writes, max_logical_writes FROM sys.dm_exec_query_stats AS s1 CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS s2 WHERE s2.objectid is null ORDER BY s1.sql_handle, s1.statement_start_offset, s1.statement_end_offset; Comments

Page 60 of 211

Issue 86: Query to find unused indexes Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 04-Oct-10 Indexing

G(0)

Description DECLARE @dbid INT SELECT @dbid = DB_ID(DB_NAME()) SELECT OBJECTNAME = OBJECT_NAME(I.OBJECT_ID), INDEXNAME = I.NAME, I.INDEX_ID FROM SYS.INDEXES I JOIN SYS.OBJECTS O ON I.OBJECT_ID = O.OBJECT_ID WHERE OBJECTPROPERTY(O.OBJECT_ID,'IsUserTable') = 1 AND I.INDEX_ID NOT IN ( SELECT S.INDEX_ID FROM SYS.DM_DB_INDEX_USAGE_STATS S WHERE S.OBJECT_ID = I.OBJECT_ID AND I.INDEX_ID = S.INDEX_ID AND DATABASE_ID = @dbid) ORDER BY OBJECTNAME, I.INDEX_ID, INDEXNAME ASC GO Comments

Page 61 of 211

Issue 87: Failed SQL Server Agent Jobs - last 7 days. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 05-Oct-10 Jobs_Query

G(0)

Description -- Variable Declarations DECLARE @PreviousDate datetime DECLARE @Year VARCHAR(4) DECLARE @Month VARCHAR(2) DECLARE @MonthPre VARCHAR(2) DECLARE @Day VARCHAR(2) DECLARE @DayPre VARCHAR(2) DECLARE @FinalDate INT
-- Initialize Variables SET @PreviousDate = DATEADD(dd, -7, GETDATE()) -- Last 7 days SET @Year = DATEPART(yyyy, @PreviousDate) SELECT @MonthPre = CONVERT(VARCHAR(2), DATEPART(mm, @PreviousDate)) SELECT @Month = RIGHT(CONVERT(VARCHAR, (@MonthPre + 1000000000)),2) SELECT @DayPre = CONVERT(VARCHAR(2), DATEPART(dd, @PreviousDate)) SELECT @Day = RIGHT(CONVERT(VARCHAR, (@DayPre + 1000000000)),2) SET @FinalDate = CAST(@Year + @Month + @Day AS INT) -- Final Logic SELECT j.[name], s.step_name, h.step_id, h.step_name, h.run_date, h.run_time, h.sql_severity, h.message, h.server FROM msdb.dbo.sysjobhistory h INNER JOIN msdb.dbo.sysjobs j ON h.job_id = j.job_id INNER JOIN msdb.dbo.sysjobsteps s ON j.job_id = s.job_id AND h.step_id = s.step_id WHERE h.run_status = 0 -- Failure AND h.run_date > @FinalDate ORDER BY h.instance_id DESC

Comments

Page 62 of 211

Issue 88: checking job history Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 06-Oct-10 Jobs_Query

G(0)

Description --'2010-10-05'
alter PROCEDURE usp_job_history '2010-10-5' @dateparam DATETIME AS SELECT dbo.sysjobhistory.server, dbo.sysjobs.name AS job_name, CASE dbo.sysjobhistory.run_status WHEN 0 THEN 'Failed' WHEN 1 THEN 'Succeeded' ELSE '???' END as run_status, dbo.sysjobhistory.run_date, dbo.sysjobhistory.run_time/10000 as run_time_hours, (run_time%10000)/100 AS run_time_minutes, (run_time%10000)%100 AS run_time_seconds , dbo.sysjobhistory.step_id, dbo.sysjobhistory.step_name, dbo.sysjobhistory.run_duration, dbo.sysjobhistory.message from dbo.sysjobhistory INNER JOIN dbo.sysjobs ON dbo.sysjobhistory.job_id = dbo.sysjobs.job_id WHERE dbo.sysjobs.category_id = 0 and dbo.sysjobhistory.run_date = datepart(yyyy,@dateparam)*10000 + datepart(mm,@dateparam)*100 + datepart(dd,@dateparam) ORDER BY dbo.sysjobhistory.server, dbo.sysjobhistory.run_date, dbo.sysjobhistory.run_time, dbo.sysjobs.name, dbo.sysjobhistory.step_id GO SELECT run_time , run_time/10000 AS run_time_hours , (run_time%10000)/100 AS run_time_minutes , (run_time%10000)%100 AS run_time_seconds , (run_time/10000 /*run_time_hours*/ * 60 * 60 /* hours to minutes to seconds*/) + ((run_time%10000)/100 /* run_time_minutes */ * 60 /* minutes to seconds */ ) + (run_time%10000)%100 AS run_time_elapsed_seconds , CONVERT(DATETIME, RTRIM(run_date)) AS Start_Date , CONVERT(DATETIME, RTRIM(run_date)) + ((run_time/10000 * 3600) + ((run_time%10000)/100*60) + (run_time%10000)%100 /*run_time_elapsed_seconds*/) / (23.999999*3600 /* seconds in a day*/) AS Start_DateTime , ((run_duration/10000 * 3600) + ((run_duration%10000)/100*60) + (run_duration%10000)%100 /*run_duration_elapsed_seconds*/) , CONVERT(DATETIME, RTRIM(run_date)) + ((run_time/10000 * 3600) + ((run_time%10000)/100*60) + (run_time%10000)%100) / (86399.9964 /* Start Date Time */) + ((run_duration/10000 * 3600) + ((run_duration%10000)/100*60) + (run_duration%10000)%100 /*run_duration_elapsed_seconds*/) / (86399.9964 /* seconds in a day*/) AS End_DateTime FROM msdb.dbo.sysjobhistory
Page 63 of 211

Comments Issue 89: Table Name of user databases-- Sys.tables Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 13-Oct-10

G(0)

Description
SELECT '['+SCHEMA_NAME(schema_id)+'].['+name+']' AS SchemaTable FROM sys.tables

Comments

Page 64 of 211

Issue 90: Performace dashboard report Error - Difference of two datetime values caused an overflow at runtime Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 21-Oct-10 Performance dashboard report

G(0)

Description

USE [msdb] GO /****** Object: StoredProcedure [MS_PerfDashboard].[usp_Main_GetSessionInfo] Script Date: 06/19/2008 15:35:54 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER procedure [MS_PerfDashboard].[usp_Main_GetSessionInfo] as begin select count(*) as num_sessions, sum(convert(bigint, s.total_elapsed_time)) as total_elapsed_time, sum(convert(bigint, s.cpu_time)) as cpu_time, sum(convert(bigint, s.total_elapsed_time)) - sum(convert(bigint, s.cpu_time)) as wait_time, --sum(convert(bigint, datediff(ms, login_time, getdate()))) - sum(convert(bigint, s.total_elapsed_time)) as idle_connection_time, --FIX to correct for sessions connected >24 days sum(convert(bigint, CAST ( DATEDIFF ( minute, login_time, getdate()) AS BIGINT)*60000 + DATEDIFF ( millisecond, DATEADD ( minute, DATEDIFF ( minute, login_time, getdate() ), login_time ),getdate() ))) - sum(convert(bigint, s.total_elapsed_time)) as idle_connection_time, case when sum(s.logical_reads) > 0 then (sum(s.logical_reads) - isnull(sum(s.reads), 0)) / convert(float, sum(s.logical_reads)) else NULL end as cache_hit_ratio from sys.dm_exec_sessions s where s.is_user_process = 0x1 end
Comments

Page 65 of 211

Issue 91: setup.sql - file for sql server 2008. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 21-Oct-10 Performance dashboard report

G(1)

Description Comments

Issue 92: How to Convert run_time int value to time. Divide the value by 1000)%100 Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 22-Oct-10 Jobs_Query

G(0)

Description select job_id,(next_run_time/10000)%100 as run_time_1 FROM msdb.dbo.sysjobschedules where (next_run_time/10000)%100= 2 Comments

Page 66 of 211

Issue 93: Different ServerPropertyCommand Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 28-Oct-10 Query-Session Level

G(0)

Description SELECT CONVERT(char(20), SELECT CONVERT(char(20), SELECT CONVERT(char(20), SELECT CONVERT(char(20), SELECT CONVERT(char(20), SELECT CONVERT(char(20), SELECT CONVERT(char(20), SELECT CONVERT(char(20), SELECT CONVERT(char(20), SELECT CONVERT(char(20), SELECT CONVERT(char(20), SELECT CONVERT(char(20), SELECT CONVERT(char(20), SELECT CONVERT(char(20), SELECT CONVERT(char(20), SELECT CONVERT(char(20), SELECT CONVERT(char(20), SELECT CONVERT(char(20), SELECT CONVERT(char(20), SELECT CONVERT(char(20), SELECT CONVERT(char(20), SELECT CONVERT(char(20), SELECT CONVERT(char(20), SELECT CONVERT(char(20), SELECT CONVERT(char(20), SELECT CONVERT(char(20), SELECT CONVERT(char(20), Comments

SERVERPROPERTY('BuildClrVersion')); SERVERPROPERTY('Collation')); SERVERPROPERTY('CollationID')); SERVERPROPERTY('ComparisonStyle')); SERVERPROPERTY('ComputerNamePhysicalNetBIOS')); SERVERPROPERTY('Edition')); SERVERPROPERTY('EditionID')); SERVERPROPERTY('EngineEdition')); SERVERPROPERTY('InstanceName')); SERVERPROPERTY('IsClustered')); SERVERPROPERTY('IsFullTextInstalled')); SERVERPROPERTY('IsIntegratedSecurityOnly')); SERVERPROPERTY('IsSingleUser')); SERVERPROPERTY('LCID')); SERVERPROPERTY('LicenseType')); SERVERPROPERTY('MachineName')); SERVERPROPERTY('NumLicenses')); SERVERPROPERTY('ProcessID')); SERVERPROPERTY('ProductVersion')); SERVERPROPERTY('ProductLevel')); SERVERPROPERTY('ResourceLastUpdateDateTime')); SERVERPROPERTY('ResourceVersion')); SERVERPROPERTY('ServerName')); SERVERPROPERTY('SqlCharSet')); SERVERPROPERTY('SqlCharSetName')); SERVERPROPERTY('SqlSortOrder')); SERVERPROPERTY('SqlSortOrderName'));

Page 67 of 211

Issue 94: Capturing Indexes That Have Been Used -IndexCategory Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 03-Nov-10 Indexing

G(0)

Description

USE AdventureWorks; go SELECT o.name Object_Name, SCHEMA_NAME(o.schema_id) Schema_name, i.name Index_name, i.Type_Desc, s.user_seeks, s.user_scans, s.user_lookups, s.user_updates FROM sys.objects AS o JOIN sys.indexes AS i ON o.object_id = i.object_id JOIN sys.dm_db_index_usage_stats AS s ON i.object_id = s.object_id AND i.index_id = s.index_id WHERE o.type = 'u' -- Clustered and Non-Clustered indexes AND i.type IN (1, 2) -- Indexes that have been updated by not used AND(s.user_seeks > 0 or s.user_scans > 0 or s.user_lookups > 0 );

Comments

Page 68 of 211

Issue 95: Indentifying Indexes that are not being used - index Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 03-Nov-10 Query-Session Level

G(0)

Description

USE AdventureWorks; go SELECT o.name Object_Name, i.name Index_name, i.Type_Desc FROM sys.objects AS o JOIN sys.indexes AS i ON o.object_id = i.object_id LEFT OUTER JOIN sys.dm_db_index_usage_stats AS s ON i.object_id = s.object_id AND i.index_id = s.index_id WHERE o.type = 'u' -- Clustered and Non-Clustered indexes AND i.type IN (1, 2) -- Indexes without stats AND (s.index_id IS NULL) OR -- Indexes that have been updated by not used (s.user_seeks = 0 AND s.user_scans = 0 AND s.user_lookups = 0 );

Comments

Page 69 of 211

Issue 96: SQL SERVER 2008 Find Index Fragmentation Details Slow Index Performance Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 24-Nov-10 Query-Session Level

G(0)

Description

SELECT ps.database_id, ps.OBJECT_ID, ps.index_id, b.name, ps.avg_fragmentation_in_percent FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS ps INNER JOIN sys.indexes AS b ON ps.OBJECT_ID = b.OBJECT_ID AND ps.index_id = b.index_id WHERE ps.database_id = DB_ID() ORDER BY ps.OBJECT_ID ---------------------------------------------------------------------------------------------------------------SELECT * FROM sys.dm_db_index_physical_stats(DB_ID(), OBJECT_ID('test_contig'), NULL, NULL , 'DETAILED') Above query returns lots of information, most of the time we only need to know Tablename, IndexName and Percentage of Fragmentation. Following query returns only three most important details mentioned earlier. I have added an extra condition where results are filtered where average fragmentation is greater than 20%. SELECT OBJECT_NAME(i.OBJECT_ID) AS TableName, i.name AS IndexName, indexstats.avg_fragmentation_in_percent FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'DETAILED') indexstats INNER JOIN sys.indexes i ON i.OBJECT_ID = indexstats.OBJECT_ID AND i.index_id = indexstats.index_id WHERE indexstats.avg_fragmentation_in_percent > 20

Comments

Page 70 of 211

Issue 97: Finding all currently blocked requests Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-Nov-10 Blocking query

G(0)

Description SELECT session_id ,status ,blocking_session_id ,wait_type ,wait_time ,wait_resource ,transaction_id FROM sys.dm_exec_requests WHERE status = N'suspended'; GO
Runnable Online Run Running Ums Sleep

Comments

Page 71 of 211

Issue 98: sql Profiler for sql server 2005 - Blocking - Events- data column and Filters. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-Nov-10 Performance Issue

G(0)

Description Error and Warnings: Exception Error and Warnings: Attention Performance: Execution Plan Sessions: Exiting Connection Stored Procedures: RPC: Starting Stored Procedures: RPC: Completed Stored Procedures: SP: Starting Stored Procedures: SP: Completed Stored Procedures: SP: StmtStarting Stored Procedures: SP: StmtCompleted Transactions: SQLTransaction TSQL: SQL:BatchStarting TSQL: SQL:BatchCompleted
Data Columns Group: SPID EventClass TextData IntegerData BinaryData ApplicationName NTUserName LoginName StartTime EndTime Filters Trace Event Criteria: Severity (type 24 in "Less than or equal" box) Add other filters as desired to reduce a flood of too much data

Comments

Page 72 of 211

Issue 99: SAVVIS_DatabasesMaintenance_V2 Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 27-Nov-10 Backup and Restore

G(0)

Description
/ *########################################################################################## ######################### ########################################################################################### ########################## ##### ##### ##### ##### ##### Create the SAVVIS Database Maintenance Stored Procedure to Optimize Databases ##### ##### ##### ##### ##### ########################################################################################### ########################## ########################################################################################### ########################## ####################################################### ## ######################################################## ####################################################### ## ######################################################## ####################################################### ## ######################################################## ####################################################### ######################################################## ########################################################### ######################################################## ########################################################### ######################################################## ########################################################### ######################################################## ########################################################################################### ########################## ########################################################################################### ########################*/ CREATE PROCEDURE [dbo].[SAVVIS_DatabasesMaintenance_V2] @ExcludeDBs VARCHAR(MAX) = '''tempdb''', @Verbose BIT = 0, @Fragmentation INT = 50, @FreeSpace INT = 10 AS ------------------------------------------------------------------------------------------- Usage: EXEC [dbo].[SAVVIS_DatabasesMaintenance_V2] -@ExcludeDBs = [comma seperated databases], -@Verbose = [0=off, 1=on], -@Fragmentation = [0% - 100%], -@FreeSpace = [0% - 100%] --

Page 73 of 211

------------------------------------------------------------------------------------------ Excluding the following parameters (@ExcludeDBs, & @Verbose) will perform maintenance on all -- databases except tempdb, no verbose logging will be used, only Indexes above 50% Fragmentation -- will be defragmented, and all databases will be left with 10% of free space. ------------------------------------------------------------------------------------------ Example1: Prefrom Database Maintenance on all applicable databases except; (msdb, master, model, & Tempdb) -do not use verbose logging, Defragment any Index over 20% fragmentation, and leave 25% free space --EXEC dbo.[SAVVIS_DatabasesMaintenance_V2] -@ExcludeDBs = '''msdb'', ''master'', ''model'', ''tempdb''' -@Verbose = 0 -@Fragmentation = 20 -@FreeSpace = 25 ------------------------------------------------------------------------------------------- Example2: Prefrom Database Maintenance on all applicable databases except; (Tempdb), use verbose -logging, Defragment any Index over 90% fragmentation, and leave 5% free space --EXEC dbo.[SAVVIS_DatabasesMaintenance_V2] -@ExcludeDBs = '''tempdb''' -@Verbose = 1 -@Fragmentation = 90 -@FreeSpace = 5 -----------------------------------------------------------------------------------------SET NOCOUNT ON DECLARE @SVVSDatabases TABLE ([name] sysname) INSERT INTO @SVVSDatabases EXEC('SELECT [name] FROM [master].[sys].[databases] WHERE ([name] NOT IN (' + @ExcludeDBs + ')) AND ([state_desc] NOT IN (''OFFLINE'', ''RESTORING'')) AND ([is_in_standby] <> 1) AND ([source_database_id] IS NULL) AND ([is_read_only] <> 1)') DECLARE @ErrorMessage VARCHAR(MAX) DECLARE @SVVSDatabaseMaintenance_DBName SYSNAME DECLARE SVVSDatabaseMaintenance_Cursor CURSOR FOR SELECT [name] FROM @SVVSDatabases OPEN SVVSDatabaseMaintenance_Cursor FETCH NEXT FROM SVVSDatabaseMaintenance_Cursor INTO @SVVSDatabaseMaintenance_DBName WHILE @@FETCH_STATUS = 0 BEGIN CheckDatabaseIntegrity: BEGIN TRY IF (@Verbose = 1) PRINT 'Checking Database Integrity on: ' + @SVVSDatabaseMaintenance_DBName EXEC ('DBCC CHECKDB (N''' + @SVVSDatabaseMaintenance_DBName + ''') WITH NO_INFOMSGS') END TRY BEGIN CATCH IF (@Verbose = 1) BEGIN PRINT 'ERROR -- Check Database Integrity Task: ' + @SVVSDatabaseMaintenance_DBName + ' - ' + ERROR_MESSAGE() PRINT ('DBCC CHECKDB (N''' + @SVVSDatabaseMaintenance_DBName + ''') WITH NO_INFOMSGS') END SET @ErrorMessage = Replace(ERROR_MESSAGE(), '''', '') EXEC('RAISERROR(''ERROR -- Check Database Integrity Task: ' + @SVVSDatabaseMaintenance_DBName + ' - ' + @ErrorMessage + ''', 16, 1) WITH LOG')

Page 74 of 211

END CATCH IF (@@ERROR = 0) GOTO ShrinkDatabase ELSE GOTO NextDatabase ShrinkDatabase: BEGIN TRY IF (@Verbose = 1) PRINT 'Shrinking Database: ' + @SVVSDatabaseMaintenance_DBName EXEC ('DBCC SHRINKDATABASE(N''' + @SVVSDatabaseMaintenance_DBName + ''', ' + @FreeSpace + ', NOTRUNCATE) WITH NO_INFOMSGS') END TRY BEGIN CATCH IF (@Verbose = 1) BEGIN PRINT 'ERROR -- Shrink Database Task: ' + @SVVSDatabaseMaintenance_DBName + ' - ' + ERROR_MESSAGE() PRINT ('DBCC SHRINKDATABASE(N''' + @SVVSDatabaseMaintenance_DBName + ''', 10, NOTRUNCATE) WITH NO_INFOMSGS') END SET @ErrorMessage = Replace(ERROR_MESSAGE(), '''', '') EXEC('RAISERROR(''ERROR -- Shrink Database Task: ' + @SVVSDatabaseMaintenance_DBName + ' - ' + @ErrorMessage + ''', 16, 1) WITH LOG') END CATCH IF (@@ERROR = 0) GOTO ReorganizeIndex ELSE GOTO NextDatabase ReorganizeIndex: DECLARE @DatabaseID INT SET @DatabaseID = db_id(@SVVSDatabaseMaintenance_DBName) DECLARE @SVVSTablesIndexes TABLE([TableViewName] SYSNAME, [IndexName] SYSNAME) INSERT INTO @SVVSTablesIndexes EXEC('SELECT QUOTENAME(OBJECT_SCHEMA_NAME([Frag].[object_id], [Frag].[database_id])) + ''.'' + QUOTENAME(OBJECT_NAME([Frag].[object_id], [Frag].[database_id])) AS [TableViewName], [Indx].[name] AS [IndexName] FROM [master].[sys].[dm_db_index_physical_stats] ('+ @DatabaseID +', NULL, NULL, NULL, NULL) AS [Frag] INNER JOIN [' + @SVVSDatabaseMaintenance_DBName + '].[sys].[indexes] AS [Indx] ON [Indx].[object_id] = [Frag].[object_id] AND [Indx].[index_id] = [Frag].[index_id] WHERE ([Frag].[avg_fragmentation_in_percent] >= ' + @Fragmentation + ') AND ([Frag].[index_id] > 0) ') DECLARE @SVVSTableViewName SYSNAME DECLARE SVVSTableViewName_Cursor CURSOR FOR SELECT DISTINCT [TableViewName] FROM @SVVSTablesIndexes OPEN SVVSTableViewName_Cursor FETCH NEXT FROM SVVSTableViewName_Cursor INTO @SVVSTableViewName WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @SVVSIndexName SYSNAME DECLARE SVVSIndexName_Cursor CURSOR FOR SELECT DISTINCT [IndexName] FROM @SVVSTablesIndexes WHERE [TableViewName] = @SVVSTableViewName OPEN SVVSIndexName_Cursor FETCH NEXT FROM SVVSIndexName_Cursor INTO @SVVSIndexName WHILE @@FETCH_STATUS = 0 BEGIN ReoragnizeIndexes: BEGIN TRY IF (@Verbose = 1) PRINT 'Reorganizing Index: ' + @SVVSIndexName + ' for Table: ' + @SVVSTableViewName + ' on Database: ' + @SVVSDatabaseMaintenance_DBName EXEC ('ALTER INDEX [' + @SVVSIndexName + '] ON [' + @SVVSDatabaseMaintenance_DBName + '].' + @SVVSTableViewName + ' REORGANIZE WITH ( LOB_COMPACTION = ON )')

Page 75 of 211

END TRY BEGIN CATCH IF (@Verbose = 1) BEGIN PRINT 'ERROR -- Reorganizing Index Task for Index: ' + @SVVSIndexName + ' on Table: ' + @SVVSTableViewName + ' in Database: ' + @SVVSDatabaseMaintenance_DBName + ': ' + ERROR_MESSAGE() PRINT ('ALTER INDEX [' + @SVVSIndexName + '] ON [' + @SVVSDatabaseMaintenance_DBName + '].' + @SVVSTableViewName + ' REORGANIZE WITH ( LOB_COMPACTION = ON )') END SET @ErrorMessage = Replace(ERROR_MESSAGE(), '''', '') EXEC('RAISERROR(''ERROR -- Reorganizing Index Task for Index: ' + @SVVSIndexName + ' on Table: ' + @SVVSTableViewName + ' in Database: ' + @SVVSDatabaseMaintenance_DBName + ' - ' + @ErrorMessage + ''', 16, 1) WITH LOG') END CATCH UpdateStatistics: BEGIN TRY IF (@Verbose = 1) PRINT 'Updating Statistics for Table: ' + @SVVSTableViewName + ' on Database: ' + @SVVSDatabaseMaintenance_DBName EXEC('UPDATE STATISTICS [' + @SVVSDatabaseMaintenance_DBName + '].' + @SVVSTableViewName + ' [' + @SVVSIndexName + '] WITH FULLSCAN') END TRY BEGIN CATCH IF (@Verbose = 1) BEGIN PRINT 'ERROR -- Update Statistics Task: ' + @SVVSDatabaseMaintenance_DBName + ' - ' + ERROR_MESSAGE() PRINT ('UPDATE STATISTICS [' + @SVVSDatabaseMaintenance_DBName + '].' + @SVVSTableViewName + ' [' + @SVVSIndexName + '] WITH FULLSCAN') END SET @ErrorMessage = Replace(ERROR_MESSAGE(), '''', '') EXEC('RAISERROR(''ERROR -- Update Statistics Task: ' + @SVVSDatabaseMaintenance_DBName + ' - ' + @ErrorMessage + ''', 16, 1) WITH LOG') END CATCH FETCH NEXT FROM SVVSIndexName_Cursor INTO @SVVSIndexName END CLOSE SVVSIndexName_Cursor DEALLOCATE SVVSIndexname_Cursor FETCH NEXT FROM SVVSTableViewName_Cursor INTO @SVVSTableViewName END CLOSE SVVSTableViewName_Cursor DEALLOCATE SVVSTableViewName_Cursor GOTO NextDatabase NextDatabase: DELETE FROM @SVVSTablesIndexes FETCH NEXT FROM SVVSDatabaseMaintenance_Cursor INTO @SVVSDatabaseMaintenance_DBName END CLOSE SVVSDatabaseMaintenance_Cursor DEALLOCATE SVVSDatabaseMaintenance_Cursor

Comments

Page 76 of 211

Issue 100: The following query returns the total number of free pages and total free space in megabytes (MB) available in all files in tempdb. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 02-Dec-10 tempdb space related

G(0)

Description
SELECT SUM(unallocated_extent_page_count) AS [free pages], (SUM(unallocated_extent_page_count)*1.0/128) AS [free space in MB] FROM sys.dm_db_file_space_usage;

Comments Issue 101: Determining the Longest Running Transaction - in tempdb Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 02-Dec-10 tempdb space related

G(0)

Description
If the version store is using a lot of space in tempdb, you must determine what is the longest running transaction. Use this query to list the active transactions in order, by longest running transaction. SELECT transaction_id FROM sys.dm_tran_active_snapshot_database_transactions ORDER BY elapsed_time_seconds DESC;

Comments [Version: 12/2/2010 4:22:10 AM ] http://msdn.microsoft.com/en-us/library/ms176029.aspx

Page 77 of 211

Issue 103: Sysmail_allitems -- Sysmail_sentitems -- sysmail_unsentitems -- sysmail_failitems Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 04-Dec-10

G(0)

Description
Database Mail keeps copies of outgoing e-mail messages and displays them in the sysmail_allitems, sysmail_sentitems, sysmail_unsentitems, sysmail_faileditems . The status of the mail sent can be seen in sysmail_mailitems table, when the mail is sent successfully the sent_status field of the sysmail_mailitems table is set to 1 which can again be seen in sysmail_sentitems table. The mails that are failed will have the sent_status field value to 2 and those are unsent will have value 3. The log can be checked in sysmail_log table as shown below: SELECT * FROM sysmail_mailitems GO SELECT * FROM sysmail_log

Comments Issue 104: Steps to monitor long runing job from one server. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 18-Dec-10 Jobs_Query

G(0)

Description
http://searchsqlserver.techtarget.com/tip/Stored-procedure-to-monitor-long-running-jobs-in-SQL-Server-2000

Comments

Page 78 of 211

Issue 105: set clusterlog Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-Dec-10 Cluster

G(0)

Description
run at a command prompt: in windows server 2008: CLUSTER.EXE YourClusterName LOG /GEN /COPY:"C:\Temp\cluster.log" as this in command prompt where YourClusterName is is nothing but a host name.

Comments
Issue 106: Steps to install Windows cluster and sql server cluster Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 27-Dec-10 Cluster

G(1)

Description Comments

Issue 107: Preparing the SQL Server 2005 Clustering Infrastructure Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 27-Dec-10 Cluster

G(0)

Description
http://www.sql-server-performance.com/articles/clustering/cluster_infrastructure_p2.aspx

Comments

Page 79 of 211

Issue 108: SQL Server 2005 Clustering Best Practices Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 27-Dec-10 Cluster

G(0)

Description Comments

Issue 109: SQL Server 2005 Clustering Best Practice Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 27-Dec-10 Cluster

G(1)

Description Comments

Issue 110: Replication-Skip and Verbose settings Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 09-Jan-11 Replication Concept

G(0)

Description
-Subscriber [FFEMSCOMSQL01] -SubscriberDB [ODS] -Publisher [FFESQPROD01\PRODINSTANCE01] -Distributor [FFESQPROD01\PRODINSTANCE01] -DistributorSecurityMode 1 -Publication [ProdMemPub] -PublisherDB [Membership] -Continuous -Output D:\Temp\dist.txt -Outputverboselevel 2 -SkipErrors 20598

Comments

Page 80 of 211

Issue 111: Adding a Subscriber and create coresponding distribution agent job Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 16-Jan-11 Replication Concept

G(0)

Description use [Fingerprint] exec sp_addsubscription @publication = N'Fingerprint_PUB_SAVVIS', @subscriber = N'S607058SC9SQL3\SQL03', @destination_db = N'Fingerprint', @subscription_type = N'Push', @sync_type = N'automatic', @article = N'All', @update_mode = N'read only', @subscriber_type = 0
exec sp_addpushsubscription_agent @publication = N'Fingerprint_PUB_SAVVIS', @subscriber = N'S607058SC9SQL3\SQL03', @subscriber_db = N'Fingerprint', @job_login = null, @job_password = null, @subscriber_security_mode = 0, @subscriber_login = N'repl', @subscriber_password = null, @frequency_type = 64, @frequency_interval = 0, @frequency_relative_interval = 0, @frequency_recurrence_factor = 0, @frequency_subday = 0, @frequency_subday_interval = 0, @active_start_time_of_day = 0, @active_end_time_of_day = 235959, @active_start_date = 20110116, @active_end_date = 99991231, @enabled_for_syncmgr = N'False', @dts_package_location = N'Distributor'

Comments

Page 81 of 211

Issue 213: Creating Interactive SQL Login with password. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 08-Nov-12 Login_User_Schema

G(0)

Description USE [master] GO CREATE LOGIN [ACEDEV01] WITH PASSWORD=N'NLe2i3:n', DEFAULT_DATABASE=[tempdb], CHECK_EXPIRATION=OFF, CHECK_POLICY=ON GO USE [ACE] GO CREATE USER [ACEDEV01] FOR LOGIN [ACEDEV01] GO USE [ACE] GO ALTER USER [ACEDEV01] WITH DEFAULT_SCHEMA=[dbo] GO USE [ACE] GO EXEC sp_addrolemember N'db_datareader', N'ACEDEV01' GO USE [ACE] GO EXEC sp_addrolemember N'db_datawriter', N'ACEDEV01' GO
grant view definition to [ACEDEV01]

Comments Issue 214: Alter Table with not null where table already has records and data. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 16-Nov-12 DDL Changes

G(0)

Description
Alter TABLE [ivrmgr].VCE_APPL_SETTING add VCE_APPL_SETTING_TYPE_C char(10) UPDATE [ivrmgr].VCE_APPL_SETTING SET VCE_APPL_SETTING_TYPE_C = '' Alter TABLE [ivrmgr].VCE_APPL_SETTING ALTER COLUMN VCE_APPL_SETTING_TYPE_C char(10) NOT NULL

Comments

Page 82 of 211

Issue 215: How Many Dirty Page exist in each database-Sys.dm_os_Buffer_discriptors Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 30-Nov-12 Memory

G(0)

Description
select db_name(database_id) as 'Database', count(page_id) as 'Direty page' from sys.dm_os_buffer_descriptors where is_modified = 1 group by db_name(database_id) order by count(page_id) desc

Comments
Issue 216: How much space each database is consuming in data cache -- sys.dm_os_buffer_descriptors Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 30-Nov-12 Memory

G(0)

Description
Select count(*) * 8/1024 as 'Cached Size (MB)', CASE database_id when 32767 Then 'ResourceDb' else db_name(database_id) end as 'Database' from sys.dm_os_buffer_descriptors group by db_name(database_id), database_id order by 'Cached Size (MB)' desc

Comments

Page 83 of 211

Issue 217: Replication Topology- Latest By Suhas Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 20-Dec-12 Replication Concept

G(0)

Description
/* * ********************************************************************************* * PURPOSE : Getting Replication Topology * VERSION : 1.0.0.0 * RUNS ON : The Distributor Server; against the Distribution Database * Script written by Suhas De & Gaurav Mathur. * CopyRight Suhas De & Gaurav Mathur, Microsoft India GTSC, 2010. * ********************************************************************************* * This script queries the Distribution Database (and optionally the Publisher * database, if the Distributor is also a Publisher) and draws out the replication * topology. It helps us understand the replication topology and allows * various other details that we need to understand the issue and thus helps us to * troubleshoot the issue faster. * * Currently we support only SQL Server 2005 / SQL Server 2008 instances. * ********************************************************************************* */ SET NOCOUNT ON GO IF ((SELECT COUNT(*) FROM TEMPDB.SYS.TABLES WHERE NAME = '##CE') > 0) DROP TABLE ##CE GO CREATE TABLE ##CE ([DESCRIPTION] VARCHAR(100) NOT NULL, [VALUE] VARCHAR(100) NOT NULL) GO INSERT INTO ##CE VALUES('Continue', 1) GO DECLARE @CONSOLEMSG VARCHAR(1000) DECLARE @SQLVersion VARCHAR(2) SET @SQLVersion = CONVERT(VARCHAR(2), SERVERPROPERTY('ProductVersion')) IF SUBSTRING(@SQLVersion, 2, 1) = '.' SET @SQLVersion = SUBSTRING(@SQLVersion, 1, 1) IF CONVERT(INT, @SQLVersion) < 9 BEGIN SET @CONSOLEMSG=CONVERT(VARCHAR(24),GETDATE(),121)+ ' SQL Server connected to is not SQL Server 2005 or SQL Server 2008. Exiting.' RAISERROR (@CONSOLEMSG,10,1) WITH NOWAIT UPDATE ##CE SET [VALUE] = 0 WHERE [DESCRIPTION] = 'Continue' END GO IF ((SELECT [VALUE] FROM ##CE WHERE [DESCRIPTION] = 'Continue') = 1) BEGIN DECLARE @CONSOLEMSG VARCHAR(1000) DECLARE @DistInst VARCHAR(1) SELECT @DistInst = CONVERT(VARCHAR(1), ISNULL([IS_DISTRIBUTOR], 0)) FROM [MASTER].[SYS].[SERVERS] (NOLOCK) WHERE [NAME] = 'REPL_DISTRIBUTOR' AND [DATA_SOURCE] = CONVERT(SYSNAME, SERVERPROPERTY('ServerName')) IF @DistInst IS NULL OR @DistInst = '0' BEGIN SET @CONSOLEMSG=CONVERT(VARCHAR(24),GETDATE(),121)+ ' Selected instance is not a distributor instance. Exiting.' RAISERROR (@CONSOLEMSG,10,1) WITH NOWAIT UPDATE ##CE SET [VALUE] = 0 WHERE [DESCRIPTION] = 'Continue' END ELSE BEGIN SET @CONSOLEMSG = REPLACE(CONVERT(VARCHAR(256), SERVERPROPERTY('ServerName')) + ' (DISTRIBUTOR :: ' + CONVERT(VARCHAR(10), SERVERPROPERTY('ProductVersion')) + ')', '.)', ')') INSERT INTO ##CE VALUES('Distributor', @CONSOLEMSG) END

Page 84 of 211

END GO IF ((SELECT [VALUE] FROM ##CE WHERE [DESCRIPTION] = 'Continue') = 1) BEGIN DECLARE @CONSOLEMSG VARCHAR(1000) SET @CONSOLEMSG = '=============================================================' RAISERROR (@CONSOLEMSG,10,1) WITH NOWAIT SET @CONSOLEMSG = ' REPLICATION TOPOLOGY' RAISERROR (@CONSOLEMSG,10,1) WITH NOWAIT SET @CONSOLEMSG = '=============================================================' RAISERROR (@CONSOLEMSG,10,1) WITH NOWAIT SET @CONSOLEMSG = 'SELECT THE PUBLICATION-SUBSCRIPTION PAIR FOR SCOPING THE CASE' RAISERROR (@CONSOLEMSG,10,1) WITH NOWAIT SET @CONSOLEMSG = '=============================================================' RAISERROR (@CONSOLEMSG,10,1) WITH NOWAIT SET @CONSOLEMSG = ' ' RAISERROR (@CONSOLEMSG,10,1) WITH NOWAIT END GO IF ((SELECT [VALUE] FROM ##CE WHERE [DESCRIPTION] = 'Continue') = 1) BEGIN DECLARE @CONSOLEMSG VARCHAR(1000) DECLARE @DISTRIBUTIONDBNAME SYSNAME DECLARE @CURRENTDATABASE SYSNAME SELECT @DISTRIBUTIONDBNAME = NAME FROM SYS.DATABASES (NOLOCK) WHERE IS_DISTRIBUTOR = 1 SELECT @CONSOLEMSG = [VALUE] FROM ##CE WHERE [DESCRIPTION] = 'Distributor' SET @CONSOLEMSG = @CONSOLEMSG + ' (Distribution Database: ' + @DISTRIBUTIONDBNAME + ')' DELETE ##CE WHERE [DESCRIPTION] = 'Distributor' RAISERROR (@CONSOLEMSG,10,1) WITH NOWAIT SELECT @CURRENTDATABASE = DB_NAME() IF @CURRENTDATABASE <> @DISTRIBUTIONDBNAME BEGIN SET @CONSOLEMSG = ' Context Database is not the Distribution Database. Exiting.' RAISERROR (@CONSOLEMSG,10,1) WITH NOWAIT UPDATE ##CE SET [VALUE] = 0 WHERE [DESCRIPTION] = 'Continue' END END GO IF ((SELECT [VALUE] FROM ##CE WHERE [DESCRIPTION] = 'Continue') = 1) BEGIN DECLARE @CONSOLEMSG VARCHAR(1000) DECLARE @DISTRIBUTORSERVERNAME SYSNAME DECLARE @PUBLISHERNAME SYSNAME DECLARE @PUBLISHERID INT DECLARE @PUBLISHERNUMBER INT DECLARE @PUBLICATIONAME SYSNAME DECLARE @PUBLICATIONID INT DECLARE @PUBLICATIONTYPE INT DECLARE @PUBLICATIONDATABASE SYSNAME DECLARE @ALLOW_QUEUED_TRAN INT DECLARE @STMT VARCHAR(MAX) DECLARE @NUMARTICLES INT DECLARE @RESERVEDSIZE BIGINT DECLARE @USEDSIZE BIGINT DECLARE @INDEXSIZE BIGINT DECLARE @SUBSCRIBERNAME SYSNAME DECLARE @SUBSCRIPTIONDB SYSNAME DECLARE @SUBSCRIPTIONTYPE INT SET @PUBLISHERNUMBER = 0 SET @DISTRIBUTORSERVERNAME = CONVERT(SYSNAME, SERVERPROPERTY('ServerName')) SET @CONSOLEMSG = ' |- PUBLISHERS' RAISERROR (@CONSOLEMSG,10,1) WITH NOWAIT DECLARE PUBLISHERCURSOR CURSOR LOCAL READ_ONLY FOR SELECT DISTINCT S.NAME, PUB.PUBLISHER_ID FROM SYS.SERVERS (NOLOCK) S JOIN DBO.MSPUBLICATIONS (NOLOCK) PUB ON S.SERVER_ID = PUB.PUBLISHER_ID OPEN PUBLISHERCURSOR FETCH NEXT FROM PUBLISHERCURSOR INTO @PUBLISHERNAME, @PUBLISHERID WHILE @@FETCH_STATUS = 0 BEGIN SET @PUBLISHERNUMBER = @PUBLISHERNUMBER + 1 SET @CONSOLEMSG = ' |- ' + @PUBLISHERNAME + ' (Publisher ' + CONVERT(VARCHAR(10), @PUBLISHERNUMBER) + ')' RAISERROR (@CONSOLEMSG,10,1) WITH NOWAIT SET @CONSOLEMSG = ' |- PUBLICATIONS'

Page 85 of 211

RAISERROR (@CONSOLEMSG,10,1) WITH NOWAIT DECLARE PUBLICATIONCURSOR CURSOR LOCAL READ_ONLY FOR SELECT PUBLICATION, PUBLICATION_ID, PUBLICATION_TYPE, PUBLISHER_DB, ALLOW_QUEUED_TRAN FROM DBO.MSPUBLICATIONS (NOLOCK) WHERE PUBLISHER_ID = @PUBLISHERID OPEN PUBLICATIONCURSOR FETCH NEXT FROM PUBLICATIONCURSOR INTO @PUBLICATIONAME, @PUBLICATIONID, @PUBLICATIONTYPE, @PUBLICATIONDATABASE, @ALLOW_QUEUED_TRAN WHILE @@FETCH_STATUS = 0 BEGIN SET @CONSOLEMSG = ' |- ' + @PUBLICATIONAME + ' (' SET @CONSOLEMSG = @CONSOLEMSG + 'Publication ID: ' + CONVERT(VARCHAR(10), @PUBLICATIONID) + '; ' IF @PUBLICATIONTYPE = 0 BEGIN IF

Comments
Issue 218: Errror 64 = The specified network name is no longer available. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 27-Dec-12 Mirroring

G(0)

Description

Errror 64 = The specified network name is no longer available. 1. Whats the the operating System? 2. Are you able to ping each other? 3. Please post the output of below command (run from cmd) netsh int tcp show global netstat -nt | findstr /i offloaded 4. You can stop and start the endpoints for quick relief (on both servers).
ALTER ENDPOINT [Mirroring] STATE=STOPPED GO ALTER ENDPOINT [Mirroring] STATE=STARTED GO

Comments

Issue 220: The availability group 'SXXXXXXXXX01' already exists Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 28-Dec-12 AlwaysOn

G(1)

Description Comments

Page 86 of 211

Issue 221: AlwaysOn: Offloading Read-Only Workloads to Secondary Replicas Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date AlwaysOn 28-Dec-12 AlwaysOn

G(1)

Description Comments

Issue 222: Legato- Database Backup and restore Command. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 31-Dec-12 Backup and Restore

G(0)

Description -- NON-CLUSTER DOCO: -- TO BACKUP: -- xp_cmdshell 'nsrsqlsv.exe -s UXBAK102-bkup-6 -b1months -lfull cTTCSQL31A MSSQL$PRD2:DBA_CORP -MSSQL$PRD2:master MSSQL$PRD2:model MSSQL$PRD2:msdb' -- TO RESTORE A SINGLE DB: -- xp_cmdshell 'nsrsqlrc.exe -suxbak102-bkup-6 -cTTCSQL31A -Snorecover MSSQL$PRD2:DBA_CORP' -- TO RESTORE ALL DBS BACKED UP IN AN INSTANCE: -- xp_cmdshell 'nsrsqlrc.exe -suxbak102-bkup-6 -cTTCSQL31A -Snorecover MSSQL$PRD2:' --- ****** NOTE: For a Cluster restore. -- From xp_cmdshell the syntax is the same. From command line leave the instance name off. -- ex. -- nsrsqlrc.exe -suxbak102-bkup-6 -cTNCSQL01v1 -Snorecover DBA_CORP Comments

Page 87 of 211

Issue 223: SQLNexus Query -For Reading the trace after creating a PSSDIAG Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 18-Jan-13 SQLNexus-Query

G(1)

Description Comments

Issue 224: Alter database command for Stores server Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 23-Jan-13 Alter Command

G(0)

Description use master go


ALTER DATABASE ISIS MODIFY FILE (NAME = ISIS_Pri1_dat,SIZE = 204800KB) ALTER DATABASE ISIS MODIFY FILE (NAME = ISIS_Log,SIZE = 5242880KB) ALTER DATABASE ISIS MODIFY FILE (NAME = ISIS_Grp1Fi1_dat,SIZE = 2560000KB) ALTER DATABASE ISIS MODIFY FILE (NAME = ISIS_Grp1Fi2_dat,SIZE = 2560000KB) ALTER DATABASE ISIS MODIFY FILE (NAME = ISIS_Grp1Fi3_dat,SIZE = 2560000KB) ALTER DATABASE ISIS MODIFY FILE (NAME = ISIS_Grp1Fi4_dat,SIZE = 2560000KB) GO print 'Alter database ISIS command executed successfully on ' + @@servername go

Comments

Page 88 of 211

Issue 225: Alter database Command Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 28-Jan-13 Backup and Restore

G(0)

Description use master go


ALTER DATABASE ISIS MODIFY FILE (NAME = ISIS_Pri1_dat,SIZE = 204800KB) ALTER DATABASE ISIS MODIFY FILE (NAME = ISIS_Log,SIZE = 5242880KB) ALTER DATABASE ISIS MODIFY FILE (NAME = ISIS_Grp1Fi1_dat,SIZE = 2560000KB) ALTER DATABASE ISIS MODIFY FILE (NAME = ISIS_Grp1Fi2_dat,SIZE = 2560000KB) ALTER DATABASE ISIS MODIFY FILE (NAME = ISIS_Grp1Fi3_dat,SIZE = 2560000KB) ALTER DATABASE ISIS MODIFY FILE (NAME = ISIS_Grp1Fi4_dat,SIZE = 2560000KB) GO print ' Alter database command has completed successfully on ' + @@servername go

Comments
Issue 226: ReadonlY routing Document - Which I presented to Sudarshan Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 15-Jul-13 AlwaysOn

G(1)

Description Comments

Page 89 of 211

Issue 227: MAXIMIZING HARDWARE UTILIZATION WITH SQL SERVER 2012 ALWAYSON READABLE SECONDARIES Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 15-Jul-13 AlwaysOn

G(1)

Description Comments

Issue 228: C:\PortQryV2>portqry -n T2262APS0001 -p udp -e 1434 Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 15-Jul-13

G(1)

Description Comments

Page 90 of 211

Issue 229: List columns where collation doesn't match database collation Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 23-Jul-13 in

G(0)

Description

List columns where collation doesn't match database collation Below script lists all database/table/column where the column collation doesn't match the database collation. I just wrote it for a migration project and thought I'd share it. I'm sure lots of tings can be improved, but below worked just fine for me for a one-time execution on a number of servers. IF OBJECT_ID('tempdb..#res') IS NOT NULL DROP TABLE #res GO DECLARE @db sysname ,@sql nvarchar(2000) CREATE TABLE #res(server_name sysname, db_name sysname, db_collation sysname, table_name sysname, column_name sysname, column_collation sysname) DECLARE c CURSOR FOR SELECT name FROM sys.databases WHERE NAME NOT IN('master', 'model', 'tempdb', 'msdb') AND state_desc = 'ONLINE' OPEN c WHILE 1 = 1 BEGIN FETCH NEXT FROM c INTO @db IF @@FETCH_STATUS <> 0 BREAK SET @sql = 'SELECT @@SERVERNAME AS server_name ,''' + @db + ''' AS db_name ,CAST(DATABASEPROPERTYEX(''' + @db + ''', ''Collation'') AS sysname) AS db_collation ,OBJECT_NAME(c.object_id, ' + CAST(DB_ID(@db) AS sysname) + ') AS table_name ,c.name AS column_name ,c.collation_name AS column_collation FROM ' + QUOTENAME(@db) + '.sys.columns AS c INNER JOIN ' + QUOTENAME(@db) + '.sys.tables AS t ON t.object_id = c.object_id WHERE t.type = ''U'' AND c.collation_name IS NOT NULL AND c.collation_name <> CAST(DATABASEPROPERTYEX(''' + @db + ''', ''Collation'') AS sysname) '
Page 91 of 211

--PRINT @sql INSERT INTO #res EXEC(@sql) END CLOSE c DEALLOCATE c SELECT * FROM #res

Comments

Page 92 of 211

Issue 230: Which User has Permissions on database. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 26-Jul-13 Login_User_Schema

G(0)

Description
SELECT [UserName] = CASE princ.[type] WHEN 'S' THEN princ.[name] WHEN 'U' THEN ulogin.[name] COLLATE Latin1_General_CI_AI END, [UserType] = CASE princ.[type] WHEN 'S' THEN 'SQL User' WHEN 'U' THEN 'Windows User' END, [DatabaseUserName] = princ.[name], [Role] = null, [PermissionType] = perm.[permission_name], [PermissionState] = perm.[state_desc], [ObjectType] = obj.type_desc,--perm.[class_desc], [ObjectName] = OBJECT_NAME(perm.major_id), [ColumnName] = col.[name] FROM --database user sys.database_principals princ LEFT JOIN --Login accounts sys.login_token ulogin on princ.[sid] = ulogin.[sid] LEFT JOIN --Permissions sys.database_permissions perm ON perm.[grantee_principal_id] = princ.[principal_id] LEFT JOIN --Table columns sys.columns col ON col.[object_id] = perm.major_id AND col.[column_id] = perm.[minor_id] LEFT JOIN sys.objects obj ON perm.[major_id] = obj.[object_id] WHERE princ.[type] in ('S','U') UNION --List all access provisioned to a sql user or windows user/group through a database or application role SELECT [UserName] = CASE memberprinc.[type] WHEN 'S' THEN memberprinc.[name] WHEN 'U' THEN ulogin.[name] COLLATE Latin1_General_CI_AI END, [UserType] = CASE memberprinc.[type] WHEN 'S' THEN 'SQL User' WHEN 'U' THEN 'Windows User' END, [DatabaseUserName] = memberprinc.[name], [Role] = roleprinc.[name], [PermissionType] = perm.[permission_name], [PermissionState] = perm.[state_desc], [ObjectType] = obj.type_desc,--perm.[class_desc], [ObjectName] = OBJECT_NAME(perm.major_id), [ColumnName] = col.[name] FROM --Role/member associations sys.database_role_members members JOIN --Roles sys.database_principals roleprinc ON roleprinc.[principal_id] = members.[role_principal_id] JOIN --Role members (database users)

Page 93 of 211

sys.database_principals memberprinc ON memberprinc.[principal_id] = members.[member_principal_id] LEFT JOIN --Login accounts sys.login_token ulogin on memberprinc.[sid] = ulogin.[sid] LEFT JOIN --Permissions sys.database_permissions perm ON perm.[grantee_principal_id] = roleprinc.[principal_id] LEFT JOIN --Table columns sys.columns col on col.[object_id] = perm.major_id AND col.[column_id] = perm.[minor_id] LEFT JOIN sys.objects obj ON perm.[major_id] = obj.[object_id] UNION --List all access provisioned to the public role, which everyone gets by default SELECT [UserName] = '{All Users}', [UserType] = '{All Users}', [DatabaseUserName] = '{All Users}', [Role] = roleprinc.[name], [PermissionType] = perm.[permission_name], [PermissionState] = perm.[state_desc], [ObjectType] = obj.type_desc,--perm.[class_desc], [ObjectName] = OBJECT_NAME(perm.major_id), [ColumnName] = col.[name] FROM --Roles sys.database_principals roleprinc LEFT JOIN --Role permissions sys.database_permissions perm ON perm.[grantee_principal_id] = roleprinc.[principal_id] LEFT JOIN --Table columns sys.columns col on col.[object_id] = perm.major_id AND col.[column_id] = perm.[minor_id] JOIN --All objects sys.objects obj ON obj.[object_id] = perm.[major_id] WHERE --Only roles roleprinc.[type] = 'R' AND --Only public role roleprinc.[name] = 'public' AND --Only objects of ours, not the MS objects obj.is_ms_shipped = 0 ORDER BY princ.[Name], OBJECT_NAME(perm.major_id), col.[name], perm.[permission_name], perm.[state_desc], obj.type_desc--perm.[class_desc]

Comments

Page 94 of 211

Issue 231: Start SQL Server in Single user for Add builtid\Administrator Access!! Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 05-Aug-13 Login_User_Schema

G(0)

Description

Stop SQL Server


net stop mssqlserver Start SQL server in single user Mode net start mssqlserver /f create login [DHC\Z087210] for windows;

EXEC sp_addsrvrolemember 'DHC\Z087210', 'sysadmin'; GO net stop mssqlserver start service from services.msc start sql server agent

Comments

Page 95 of 211

Issue 232: generate commands to grant/deny/revoke permissions for all objects in the database Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 06-Aug-13 Login_User_Schema

G(0)

Description
SELECT p.state_desc + ' ' + p.permission_name + ' ON [' + OBJECT_SCHEMA_NAME(p.major_id) + '].[' + OBJECT_NAME(p.major_id) + ']' + CASE WHEN p.state_desc IN ('GRANT','DENY') THEN ' TO ' WHEN p.state_desc IN ('REVOKE') THEN ' FROM ' END + '[' + USER_NAME(p.grantee_principal_id) + '];' FROM sys.database_permissions p INNER JOIN sys.database_principals dp ON p.grantee_principal_id = dp.principal_id INNER JOIN sys.objects o ON p.major_id = o.[object_id] WHERE p.class_desc = 'OBJECT_OR_COLUMN' AND OBJECT_SCHEMA_NAME(p.major_id) != 'sys' AND OBJECT_NAME(p.major_id) NOT LIKE 'ZZ%' ORDER BY o.type_desc, OBJECT_SCHEMA_NAME(p.major_id), OBJECT_NAME(p.major_id)

Comments

Page 96 of 211

Issue 233: principal_name,principal_type_desc,login,class_desc,object_name,Permission_name,permission_state_desc,role_name Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 06-Aug-13 Login_User_Schema

G(0)

Description
WITH perms_cte(principal_name,principal_id, principal_type_desc,class_desc, [object_name], permission_name, permission_state_desc, login ) as ( select USER_NAME(p.grantee_principal_id) AS principal_name, dp.principal_id, dp.type_desc AS principal_type_desc, p.class_desc, OBJECT_NAME(p.major_id) AS [object_name], p.permission_name, p.state_desc AS permission_state_desc, sp.name as login from sys.database_permissions p p.grantee_principal_id = dp.principal_id

left JOIN sys.database_principals dp on

left Join sys.server_principals sp on dp.sid = sp.sid ) -- users SELECT p.principal_name, p.principal_type_desc, login, p.class_desc, p.[object_name], p.permission_name, p.permission_state_desc, cast('<granted explicit>' as sysname) as role_name FROM UNION -- role members SELECT rm.member_principal_name, rm.principal_type_desc, rm.login, p.class_desc, p.[object_name], p.permission_name, coalesce(p.permission_state_desc, '<Member of fixed database-role:>'), rm.role_name FROM perms_cte p perms_cte p

right outer JOIN ( select role_principal_id, dp.type_desc as principal_type_desc, member_principal_id,user_name(member_principal_id) as member_principal_name,user_name(role_principal_id) as role_name, sp.name as login from sys.database_role_members rm

Page 97 of 211

INNER

JOIN sys.database_principals dp ON

rm.member_principal_id = dp.principal_id

left Join sys.server_principals sp on dp.sid = sp.sid ) rm ON rm.role_principal_id = p.principal_id

order by 2, 1, 4, 5, 6, 8

Comments Issue 234: MSSQLSERVER_2 Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 06-Aug-13 Database Engine Issue

G(0)

Description

An error has occurred while establishing a connection to the server. When connecting to SQL Server, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) (.Net SqlClient Data Provider)
Explanation

SQL Server did not respond to the client request because the server is probably not started User Action: make sure Server is started.
Comments Issue 235: Connectivity Issue from clients to Server -- Check the link _Excellent.. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 06-Aug-13 Database Engine Issue

G(1)

Description
http://msdn.microsoft.com/en-us/library/bb326280.aspx

Comments

Page 98 of 211

Issue 236: Find which user and hostname dropped a table in a database Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 08-Aug-13 DDL Changes

G(0)

Description

A developer came to me demanding to know who deleted One table he had been using. But i have a problem every developer using same user login, suddenly i thought if i can find HostName than my problem will be solved. I spent some minute to write this query :... Details : find which user and hostname dropped a table in a database. ----------------------------------------------------------------------------------------------Select LoginName,ObjectName,ObjectType,Name,HostName from fn_trace_gettable(CONVERT(VARCHAR(150), ( SELECT TOP 1 value FROM [fn_trace_getinfo](NULL) WHERE [property] = 2 )),1) T join Sys.trace_events TE ON T.EventClass = TE.trace_event_id and T.ObjectName is not null and TE.name='Object:Deleted'

Comments

Page 99 of 211

Issue 237: SQL Server - PREEMPTIVE_OS_WRITEFILEGATHER and how to reduce it Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 09-Aug-13 Performance Issue

G(0)

Description

SQL Server - PREEMPTIVE_OS_WRITEFILEGATHER and how to reduce it 25 October,2012 by Jack Vamvas The SQL Server wait type: PREEMPTIVE_OS_WRITEFILEGATHER indicates you have Long Autogrow events. Its usually accompanied by SQL Server performance problems. A typical situation where the PREEMPTIVE_OS_WRITEFILEGATHER appears is in large database restores.

Notes on methods to resolve:


1) Instant file initialization is not turned on. This means the data files are zeroed out as part of the grow process. Turning on instant file initialization will help will help data files, and wont assist in Log file growth 2) Consider not relying on autogrow. Plan the file sizes and manually set the size. Focus on using autogrow for exceptional circumstances. It is not always straightforward to plan for growth , particularly with modelling applications which act as massive number crunching applications. 3) If you want to use autogrow , then consider using smaller file growth sizes, either as fixed value or % growth 4) Use DBCC SQLPERF('logspace') and identify large LDF files which have a low Log Space Used percentage. When a RESTORE occurs , the RESTORE will attempt to recreate the full size of the LDF file. Consider shrinking the log file before BACKUP 5) If you are stuck in this situation , of waiting for a long time in Autogrow mode it will get eventually finish. Minimise any other activity on disk headers. Quite often this situation arises on shared arrays with other application.
Comments

Page 100 of 211

Issue 238: LOGBUFFER Wait type Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 09-Aug-13 Performance Issue

G(0)

Description

LOGBUFFER Occurs when a task is waiting for space in the log buffer to store a log record. Consistently high values may indicate that the log devices cannot keep up with the amount of log being generated by the server. =====

Reducing LOGBUFFER wait:


There are several suggestions to reduce this wait stats: Move Transaction Log to Separate Disk from mdf and other files. (Make sure your drive where your LDF is has no IO bottleneck issues). Avoid cursor-like coding methodology and frequent commit statements. Find the most-active file based on IO stall time, as shown in the script written over here. You can also use fn_virtualfilestats to find IO-related issues using the script mentioned over here. Check the IO-related counters (PhysicalDisk:Avg.Disk Queue Length, PhysicalDisk:Disk Read Bytes/sec and PhysicalDisk :Disk Write Bytes/sec) for additional details. Read about them over

Comments Issue 239: process to increase the tempdb-log file. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 10-Aug-13 tempdb space related

G(0)

Description USE [master] GO ALTER DATABASE [tempdb] MODIFY FILE ( NAME = N'templog', MAXSIZE = 46137344KB ) GO Comments

Page 101 of 211

Issue 240: How to create Named Pipe Alias.. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 10-Aug-13 in

G(0)

Description
how to create Named Pipe Alias =========================== Alias name SQLAgentAlias Pipe Name :\\T3895SQLPRD01\pipe\MSSQL$PRD1\sql\query protocol :NamedPipes Server : T3895SQLPRD01 =======================

Comments Issue 241: How To start SQL Server Agent in Console Mode.. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 10-Aug-13 Sql Server Internal concept

G(0)

Description
C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Binn\SQLAGENT90.EXE" -i PRD1 -c -v

Comments

Page 102 of 211

Issue 242: Different KB Article.. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 10-Aug-13 support.microsoft.com

G(0)

Description
====================================================================== 943525 --> You cannot start the SQL Server Agent service of a failover cluster of SQL Server 2005 if the build of SQL Server is 3179 or a later build --> http://support.microsoft.com/kb/943525 ======================================================================= ==================== 918992 --> How to transfer logins and passwords between instances of SQL Server http://support.microsoft.com/kb/918992 ========================== ========================= 294453-->How to set up SQL Server to listen on multiple static TCP ports ========================= ============================ 934749--> Error message when you try to install a SQL Server 2005 service pack from the existing active node: "The product instance <InstanceName> has been patched with more recent updates" http://support.microsoft.com/kb/934749 ============================ ======== 2674319-->Bugs that are fixed in SQL Server 2012 Service Pack 1 ================================================= ================================================= 823938-->How to configure SQL Server to listen on a specific port =================================================

Comments Issue 243: SQL Server Version Information!!! Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 11-Aug-13 in

G(0)

Description
http://sqlserverbuilds.blogspot.in/

Comments

Page 103 of 211

Issue 244: DBCC FREEPROCCACHE - For a cached query in sql server.. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 12-Aug-13 Memory

G(0)

Description
- Example 1 (Sledgehammer) -- Remove all elements from the plan cache for the entire instance DBCC FREEPROCCACHE; -- Flush the cache and suppress the regular completion message -- "DBCC execution completed. If DBCC printed error messages, contact your system administrator." DBCC FREEPROCCACHE WITH NO_INFOMSGS;

-- Example 2 (Ballpeen hammer) -- Remove all elements from the plan cache for one database -- Get DBID from one database name first DECLARE @intDBID INT; SET @intDBID = (SELECT [dbid] FROM master.dbo.sysdatabases WHERE name = 'AdventureWorks'); -- Flush the procedure cache for one database only DBCC FLUSHPROCINDB (@intDBID);

-- Example 3 (Scalpel) -- Remove one plan from the cache -- Get the plan handle for a cached plan SELECT cp.plan_handle, st.[text] FROM sys.dm_exec_cached_plans AS cp CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS st WHERE [text] LIKE N'%/* GetOnlineSearchResultsMonday %'; -- Remove the specific plan from the cache using the plan handle DBCC FREEPROCCACHE (0x05000800F7BA926C40C15055070000000000000000000000);

Comments

Page 104 of 211

Issue 112: Display Replication Topology-Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 16-Jan-11 Replication Concept

G(0)

Description SET NOCOUNT ON GO IF ((SELECT COUNT(*) FROM TEMPDB.SYS.TABLES WHERE NAME = '##CE') > 0) DROP TABLE ##CE GO CREATE TABLE ##CE ([DESCRIPTION] VARCHAR(100) NOT NULL, [VALUE] VARCHAR(100) NOT NULL) GO INSERT INTO ##CE VALUES('Continue', 1) GO DECLARE @CONSOLEMSG VARCHAR(1000) DECLARE @SQLVersion VARCHAR(2) SET @SQLVersion = CONVERT(VARCHAR(2), SERVERPROPERTY('ProductVersion')) IF SUBSTRING(@SQLVersion, 2, 1) = '.' SET @SQLVersion = SUBSTRING(@SQLVersion, 1, 1) IF CONVERT(INT, @SQLVersion) < 9 BEGIN SET @CONSOLEMSG=CONVERT(VARCHAR(24),GETDATE(),121)+ ' SQL Server connected to is not SQL Server 2005 or SQL Server 2008. Exiting.' RAISERROR (@CONSOLEMSG,10,1) WITH NOWAIT UPDATE ##CE SET [VALUE] = 0 WHERE [DESCRIPTION] = 'Continue' END GO IF ((SELECT [VALUE] FROM ##CE WHERE [DESCRIPTION] = 'Continue') = 1) BEGIN DECLARE @CONSOLEMSG VARCHAR(1000) DECLARE @DistInst VARCHAR(1) DECLARE @BitEd VARCHAR(100) DECLARE @xIndex INT SELECT @DistInst = CONVERT(VARCHAR(1), ISNULL([IS_DISTRIBUTOR], 0)) FROM [MASTER].[SYS].[SERVERS] (NOLOCK) WHERE [NAME] = 'REPL_DISTRIBUTOR' AND [DATA_SOURCE] = CONVERT(SYSNAME, SERVERPROPERTY('ServerName')) IF @DistInst IS NULL OR @DistInst = '0' BEGIN SET @CONSOLEMSG=CONVERT(VARCHAR(24),GETDATE(),121)+ ' Selected instance is not a distributor instance. Exiting.' RAISERROR (@CONSOLEMSG,10,1) WITH NOWAIT UPDATE ##CE SET [VALUE] = 0 WHERE [DESCRIPTION] = 'Continue' END ELSE BEGIN SET @CONSOLEMSG = REPLACE(CONVERT(VARCHAR(256), SERVERPROPERTY('ServerName')) + ' (DISTRIBUTOR :: ' + CONVERT(VARCHAR(10), SERVERPROPERTY('ProductVersion')) + ')', '.)', '') SELECT @BitEd = @@VERSION SELECT @xIndex = CHARINDEX('X', UPPER(@BitEd)) SELECT @BitEd = SUBSTRING(UPPER(@BitEd), @xIndex, 3) SET @CONSOLEMSG = @CONSOLEMSG + ' ' + @BitEd + ')' INSERT INTO ##CE VALUES('Distributor', @CONSOLEMSG) END END GO IF ((SELECT [VALUE] FROM ##CE WHERE [DESCRIPTION] = 'Continue') = 1) BEGIN

Page 105 of 211

DECLARE @CONSOLEMSG VARCHAR(1000) SET @CONSOLEMSG = '=============================================================' RAISERROR (@CONSOLEMSG,10,1) WITH NOWAIT SET @CONSOLEMSG = ' REPLICATION TOPOLOGY' RAISERROR (@CONSOLEMSG,10,1) WITH NOWAIT SET @CONSOLEMSG = '=============================================================' RAISERROR (@CONSOLEMSG,10,1) WITH NOWAIT SET @CONSOLEMSG = 'SELECT THE PUBLICATION-SUBSCRIPTION PAIR FOR SCOPING THE CASE' RAISERROR (@CONSOLEMSG,10,1) WITH NOWAIT SET @CONSOLEMSG = '=============================================================' RAISERROR (@CONSOLEMSG,10,1) WITH NOWAIT SET @CONSOLEMSG = ' ' RAISERROR (@CONSOLEMSG,10,1) WITH NOWAIT END GO IF ((SELECT [VALUE] FROM ##CE WHERE [DESCRIPTION] = 'Continue') = 1) BEGIN DECLARE @CONSOLEMSG VARCHAR(1000) DECLARE @DISTRIBUTIONDBNAME SYSNAME DECLARE @CURRENTDATABASE SYSNAME SELECT @DISTRIBUTIONDBNAME = NAME FROM SYS.DATABASES (NOLOCK) WHERE IS_DISTRIBUTOR = 1 SELECT @CONSOLEMSG = [VALUE] FROM ##CE WHERE [DESCRIPTION] = 'Distributor' SET @CONSOLEMSG = @CONSOLEMSG + ' (Distribution Database: ' + @DISTRIBUTIONDBNAME + ')' DELETE ##CE WHERE [DESCRIPTION] = 'Distributor' RAISERROR (@CONSOLEMSG,10,1) WITH NOWAIT SELECT @CURRENTDATABASE = DB_NAME() IF @CURRENTDATABASE <> @DISTRIBUTIONDBNAME BEGIN SET @CONSOLEMSG = ' Context Database is not the Distribution Database. Exiting.' RAISERROR (@CONSOLEMSG,10,1) WITH NOWAIT UPDATE ##CE SET [VALUE] = 0 WHERE [DESCRIPTION] = 'Continue' END END GO IF ((SELECT [VALUE] FROM ##CE WHERE [DESCRIPTION] = 'Continue') = 1) BEGIN DECLARE @CONSOLEMSG VARCHAR(1000) DECLARE @DISTRIBUTORSERVERNAME SYSNAME DECLARE @PUBLISHERNAME SYSNAME DECLARE @PUBLISHERID INT DECLARE @PUBLISHERNUMBER INT DECLARE @PUBLICATIONAME SYSNAME DECLARE @PUBLICATIONID INT DECLARE @PUBLICATIONTYPE INT DECLARE @PUBLICATIONDATABASE SYSNAME DECLARE @ALLOW_QUEUED_TRAN INT DECLARE @STMT VARCHAR(MAX) DECLARE @NUMARTICLES INT DECLARE @RESERVEDSIZE BIGINT DECLARE @USEDSIZE BIGINT DECLARE @INDEXSIZE BIGINT

Page 106 of 211

DECLARE @SUBSCRIBERNAME SYSNAME DECLARE @SUBSCRIPTIONDB SYSNAME DECLARE @SUBSCRIPTIONTYPE INT SET @PUBLISHERNUMBER = 0 SET @DISTRIBUTORSERVERNAME = CONVERT(SYSNAME, SERVERPROPERTY('ServerName')) SET @CONSOLEMSG = ' |- PUBLISHERS' RAISERROR (@CONSOLEMSG,10,1) WITH NOWAIT DECLARE PUBLISHERCURSOR CURSOR LOCAL READ_ONLY FOR SELECT DISTINCT S.NAME, PUB.PUBLISHER_ID FROM SYS.SERVERS (NOLOCK) S JOIN DBO.MSPUBLICATIONS (NOLOCK) PUB ON S.SERVER_ID = PUB.PUBLISHER_ID OPEN PUBLISHERCURSOR FETCH NEXT FROM PUBLISHERCURSOR INTO @PUBLISHERNAME, @PUBLISHERID WHILE @@FETCH_STATUS = 0 BEGIN SET @PUBLISHERNUMBER = @PUBLISHERNUMBER + 1 SET @CONSOLEMSG = ' |- ' + @PUBLISHERNAME + ' (Publisher ' + CONVERT(VARCHAR(10), @PUBLISHERNUMBER) + ')' RAISERROR (@CONSOLEMSG,10,1) WITH NOWAIT SET @CONSOLEMSG = ' |- PUBLICATIONS' RAISERROR (@CONSOLEMSG,10,1) WITH NOWAIT DECLARE PUBLICATIONCURSOR CURSOR LOCAL READ_ONLY FOR SELECT PUBLICATION, PUBLICATION_ID, PUBLICATION_TYPE, PUBLISHER_DB, ALLOW_QUEUED_TRAN FROM DBO.MSPUBLICATIONS (NOLOCK) WHERE PUBLISHER_ID = @PUBLISHERID OPEN PUBLICATIONCURSOR FETCH NEXT FROM PUBLICATIONCURSOR INTO @PUBLICATIONAME, @PUBLICATIONID, @PUBLICATIONTYPE, @PUBLICATIONDATABASE, @ALLOW_QUEUED_TRAN WHILE @@FETCH_STATUS = 0 BEGIN SET @CONSOLEMSG = ' |- ' + @PUBLICATIONAME + ' (' SET @CONSOLEMSG = @CONSOLEMSG + 'Publication ID: ' + CONVERT(VARCHAR(10), @PUBLICATIONID) + '; '

Page 107 of 211

IF @PUBLICATIONTYPE = 0 BEGIN IF @ALLOW_QUEUED_TRAN = 0 SET @CONSOLEMSG = @CONSOLEMSG + 'Publication type: Transactional (1-way); ' ELSE SET @CONSOLEMSG = @CONSOLEMSG + 'Publication type: Transactional (2-way); ' END ELSE IF @PUBLICATIONTYPE = 1 SET @CONSOLEMSG = @CONSOLEMSG + 'Publication type: Snapshot; ' ELSE IF @PUBLICATIONTYPE = 2 SET @CONSOLEMSG = @CONSOLEMSG + 'Publication type: Merge; ' SET @CONSOLEMSG = @CONSOLEMSG + 'Publication database: ' + @PUBLICATIONDATABASE + ')' RAISERROR (@CONSOLEMSG,10,1) WITH NOWAIT SET @CONSOLEMSG = 'XXX' IF @PUBLICATIONTYPE < 2 BEGIN SET @CONSOLEMSG = ' |- ARTICLES' RAISERROR (@CONSOLEMSG,10,1) WITH NOWAIT SELECT @NUMARTICLES = COUNT(ARTICLE_ID) FROM MSARTICLES (NOLOCK) WHERE PUBLICATION_ID = @PUBLICATIONID AND PUBLISHER_DB = @PUBLICATIONDATABASE SET @CONSOLEMSG = ' |- ' + CONVERT(VARCHAR(10), @NUMARTICLES) + ' article(s)' END ELSE BEGIN IF @DISTRIBUTORSERVERNAME = @PUBLISHERNAME BEGIN

Comments

Page 108 of 211

Issue 113: dropping a specific article Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 16-Jan-11 Replication Concept

G(0)

Description sp_dropsubscription @publication= 'MEMPRDPUB', @article= 'person' ,@subscriber= 'FFEMSCOMSQL01', @destination_db= 'ods'
And then dropped the article with command :

sp_droparticle

@publication= 'MEMPRDPUB', @article='person', @force_invalidate_snapshot=1

Comments

Page 109 of 211

Issue 114: Steps to drop replication from Scratch.. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 17-Jan-11 Replication Concept

G(0)

Description --sp_dropdistributor @no_checks = 1


--select @@SERVERNAME -- This script uses sqlcmd scripting variables. They are in the form -- $(MyVariable). For information about how to use scripting variables -- on the command line and in SQL Server Management Studio, see the -- "Executing Replication Scripts" section in the topic -- "Programming Replication Using System Stored Procedures". -- Disable publishing and distribution. DECLARE @distributionDB AS sysname; DECLARE @publisher AS sysname; DECLARE @publicationDB as sysname; SET @distributionDB = N'distribution'; SET @publisher = N'BLR1LS393493'; SET @publicationDB = N'AdventureWorks'; -- Disable the publication database. USE [AdventureWorks] EXEC sp_removedbreplication @publicationDB; -- Remove the registration of the local Publisher at the Distributor. USE master EXEC sp_dropdistpublisher @publisher; -- Delete the distribution database. EXEC sp_dropdistributiondb @distributionDB; -- Remove the local server as a Distributor. EXEC sp_dropdistributor; GO

Comments

Page 110 of 211

Issue 115: Configure Peer to Peer replication in sql server 2008 - By Yan Pan Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 17-Jan-11 Replication Concept

G(0)

Description
--http://www.databasejournal.com/article.php/3727886

Comments

Issue 116: Log Shipping - how to check which is last copied and last restored file. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 19-Jan-11 Log Shipping

G(0)

Description select

secondary_server, secondary_database, last_copied_file, last_copied_date, last_restored_file, last_restored_date from dbo.log_shipping_monitor_secondary where secondary_database = 'YourDatabaseName'

Comments Issue 117: Allow_Page_locks = ON-- what is Meaning of it and script Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 20-Jan-11 Indexing

G(0)

Description USE [DMEGMACDM] GO ALTER INDEX [CT_slpProspect_AccNum] ON [dbo].[slpProspect] SET ( ALLOW_PAGE_LOCKS = ON ) GO Comments

Page 111 of 211

Issue 118: What are different physical operator. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 21-Jan-11

G(0)

Description
UPDATE [dbo].[PersonMarketingPreference] SET Operation = 'D', LogMarker = getdate() where [PersonID] = @pkc1 and [MarketingPreferenceID] = @pkc2 and [NotificationTypeID] = @pkc3

Comments

Page 112 of 211

Issue 119: Map All Orphan Users to Logins else create login and map Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 22-Jan-11 Login_User_Schema

G(0)

Description

Once of my customer asked for an "automated" script which would find all the users, which are not mapped to login and map them. Below is the logic which can be used. <<<<<<<<<< PLEASE READ DISCLAIMER >>>>>> If (login not exists) create login and map login with user else map login with user <Replace MYDB and Password as appropriate> Idea taken from http://support.microsoft.com/kb/274188 Below is the script for above Logic USE MYDB GO SET NOCOUNT ON -- Declare Variables DECLARE @user_name NVARCHAR(128), @login_name NVARCHAR(128), @err_msg VARCHAR(80), @str VARCHAR(250) -- Find all users in the database MyDB which are orphan. DECLARE FIX_LOGIN_USER INSENSITIVE CURSOR FOR SELECT NAME FROM SYSUSERS WHERE ISSQLUSER = 1 AND (SID IS NOT NULL AND SID <> 0x0) AND SUSER_SNAME(SID) IS NULL ORDER BY NAME OPEN FIX_LOGIN_USER FETCH NEXT FROM FIX_LOGIN_USER INTO @user_name WHILE @@FETCH_STATUS = 0 BEGIN SELECT @login_name = NULL SELECT @login_name = LOGINNAME FROM MASTER.DBO.SYSLOGINS WHERE LOGINNAME = @user_name IF (@login_name IS NULL) BEGIN SELECT @err_msg = 'matching login does not exists for ' + @user_name PRINT @err_msg PRINT 'creating login for ' + @user_name SELECT @str = NULL
Page 113 of 211

SELECT @str = 'exec master.dbo.sp_addlogin ' + +'''' + @user_name + '''' + ' ,' + '''password@123''' + ' , ' + '''MyDB''' SELECT @str EXEC( @str) PRINT 'created and now fixing ......' EXEC SP_CHANGE_USERS_LOGIN 'update_one' , @user_name , @user_name IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN SELECT @err_msg = 'error creating login for ' + @user_name PRINT @err_msg END END ELSE BEGIN PRINT ' Only fixing ......' EXEC SP_CHANGE_USERS_LOGIN 'update_one' , @user_name , @login_name IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN SELECT @err_msg = 'error updating login for ' + @user_name PRINT @err_msg END END FETCH NEXT FROM FIX_LOGIN_USER INTO @user_name END CLOSE FIX_LOGIN_USER DEALLOCATE FIX_LOGIN_USER GO SET NOCOUNT OFF
Comments

Page 114 of 211

Issue 120: sp_replcmds(Log reader)- Reader thread. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 23-Jan-11 Replication Concept

G(0)

Description

LogReader Reader thread is reading the Transaction Log via stored procedure sp_replcmds, a wrapper for xp_replcmds. It scans the transaction log for transactions marked for replication, skipping not replicated transactions.
Comments Issue 121: sp_Msadd_replcmds-- LogReader Writer thread. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 23-Jan-11 Replication Concept

G(0)

Description

LogReader Writer thread writes queued transaction from the Reader thread into the Distribution database using sp_MSadd_replcmds.
Comments Issue 122: sp_Msget_repl_commands - Distributor Reader thread. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 23-Jan-11

G(0)

Description

Distribution Reader thread executes sp_MSget_repl_commands query to retrieve pending commands from the Distribution database and storing in an internal queue.
Comments

Page 115 of 211

Issue 123: Distributor Writer Thread -- sp_Msupd,sp_Msins,sp_Msdel Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 23-Jan-11

G(0)

Description

Distribution Writer thread writing queue commands to the Subscriber via parameterized stored procedures prefixed with sp_MSupd..., sp_MSins..., sp_MSdel... to apply individual row changes to each article at the subscriber.
Comments Issue 124: Mslogreader_history and Msdistribution_history Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 23-Jan-11

G(0)

Description

Log Reader and Distributor are also executing a history thread writing summary data to MSlogreader_history and MSdistribution_history system tables of the distribution database.
Comments
Issue 125: To see a list of the Replication Jobs, run the query below Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 23-Jan-11 Replication Concept

G(0)

Description

SELECT name, description, enabled from MSDB..sysjobs WHERE category_id>10 and category_id<20
Comments

Page 116 of 211

Issue 126: Sys.dm_repl_traninfo DMV for measure -sys.dm_repl_traninfo number of non-replicated vs. replicated transactions

FROM sys.dm_repl_traninfo Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 23-Jan-11 Replication Concept

G(0)

Description

SELECT dbid, begin_lsn, commit_lsn, rows, cmds_in_tran FROM sys.dm_repl_traninfo. --http://blogs.msdn.com/b/chrissk/archive/2009/05/25/transactional-replication-conversations.aspx number of non-replicated vs. Replicated transactions
Comments Issue 127: Records marked for Replications vs Total records in the log. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 23-Jan-11 Replication Concept

G(0)

Description

-- Total records in the log SELECT count(*) FROM ::fn_dblog(NULL, NULL) GO -- Records marked for REPLICATION SELECT count(*) FROM ::fn_dblog(NULL, NULL) WHERE Description='REPLICATE' GO
Comments

Page 117 of 211

Issue 128: Distribution Agent Reader Latency Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 23-Jan-11 Replication Concept

G(0)

Description Comments

Issue 129: How to release unused space from database files -- DBCC ShrinkFile(N'',0,truncateonly) Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 24-Jan-11

G(0)

Description USE [HUBProd_Comp] GO DBCC SHRINKFILE (N'HUB.mdf' , 0, TRUNCATEONLY) GO Comments Issue 130: Mirroring -link Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 24-Jan-11 Mirroring

G(0)

Description
http://social.msdn.microsoft.com/Forums/en/sqldatabasemirroring/thread/bc28b3e3a4a9-486e-9507-8450f070de8a

Comments

Page 118 of 211

Issue 131: xp_readerrorlog() returned error 3, 'The system cannot find the path specified.' Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-Jan-11 Corruption

G(0)

Description
Issue : When I am giving command sp_readerrorlog 0,1 --- I am able to see errorlog file but when I give sp_readerrorlog 0,2 -- it gives the error like
Msg 22004, Level 16, State 1, Line 0 xp_readerrorlog() returned error 3, 'The system cannot find the path specified.'

Generally it should show output of sqlagent.out file output which it is not showing,

I checked the server and found sqlagent.out which is in K:\MSSQL10.S605181CH3SQL04\MSSQL\Log \sqlagent.out is not updated since May-2010. And when navigated further registry Hkey_local_machine\software\microsoft\microsoft sql server \mssql10.s605181ch3sql04\sqlserveragent key errorlog value is empty. Currently the value is empty. It should not be empty

Resolution: 1. We should require to raise a change for the windows team to update the value of registry key value of sql server agent errorlog value with -- K:\MSSQL10.S605181CH3SQL04\MSSQL\Log \SQLAGENT.OUT. 2. Then restart sql server agent, then it will start working. For further clarification please check the link : http://connect.microsoft.com/SQLServer/feedback/details/509766/property-errorlogfile-is-not-available-forjobserver , last 2 comment of ErikBitemo..

Comments

Page 119 of 211

Issue 132: Safety FULL without a witness- Fail over Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 29-Jan-11 Mirroring

G(0)

Description
ALTER DATABASE <database name> SET PARTNER OFF RESTORE DATABASE <database name> WITH RECOVERY This scenario provides high safety, but automatic failover is not allowed. In the event of failure of the principal, the database service becomes unavailable. You need manual intervention to make the database service available. You must break the mirroring session and then recover the mirror database. For example, prior to the failure, Server_A and Server_B acted as principal and mirror respectively. Server_A fails. You need to execute the following on Server_B to make the database service available:

Comments Issue 133: ODS -Replication Script. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 02-Feb-11 Replication Concept

G(1)

Description Comments

Issue 135: REDO Phase Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 15-Feb-11 Sql Server Internal concept

G(0)

Description
1) Start sql server service. 2 database will go to recovery phase. 3) Sql Server T-Log file on the disk will check all LSN & it will try to find all commited transaction. 4) it will search its corresponding data pages, it will find it from .mdf/.ndf file. 5) if the page is having the change as per transaction then its okay. 6) if not -- then take the page to the data cache and commit that change again.

Comments

Page 120 of 211

Issue 136: UNDO Phase Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 15-Feb-11 Sql Server Internal concept

G(0)

Description
1) Start sql server service. 2 database will go to recovery phase 3) Sql Server T-Log file on the disk will check all LSN & it will try to find all uncommited transaction. 4) it will search its corresponding data pages, it will find it from .mdf/.ndf file. 5) if the page is having uncommited change. 6) then move the page from data file to data cache 7) then uncommit the change.

Comments Issue 137: Analysis Phase Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 15-Feb-11 Corruption

G(0)

Description
During the analysis phase, a background thread reads the Transaction Log File(s) of the database, from the last marked CheckPoint till the end of the file, and analyzes the records in the Transaction Log File(s). If this phase completes successfully, the recovery process moves to the next phase called the redo phase, and later into the undo phase.

Comments Issue 138: Query retrieves transaction details for a particular session:Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 15-Feb-11 Transaction log related queries

G(0)

Description

SELECT transaction_id, database_id, database_transaction_begin_time, database_transaction_type, database_transaction_log_record_count, database_transaction_log_bytes_used, database_transaction_log_bytes_reserved, database_transaction_begin_lsn, database_transaction_last_lsn FROM sys.dm_tran_database_transactions a INNER JOIN sys.dm_tran_locks b ON a.transaction_id = b.request_owner_id
Comments

Page 121 of 211

Issue 139: Determining space used for each table in a SQL Server database Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 21-Feb-11

G(0)

Description
BEGIN try DECLARE @table_name VARCHAR(500) ; DECLARE @schema_name VARCHAR(500) ; DECLARE @tab1 TABLE( tablename VARCHAR (500) collate database_default , schemaname VARCHAR(500) collate database_default ); DECLARE @temp_table TABLE ( tablename sysname , row_count INT , reserved VARCHAR(50) collate database_default , data VARCHAR(50) collate database_default , index_size VARCHAR(50) collate database_default , unused VARCHAR(50) collate database_default ); INSERT INTO @tab1 SELECT t1.name , t2.name FROM sys.tables t1 INNER JOIN sys.schemas t2 ON ( t1.schema_id = t2.schema_id ); DECLARE c1 CURSOR FOR SELECT t2.name + '.' + t1.name FROM sys.tables t1 INNER JOIN sys.schemas t2 ON ( t1.schema_id = t2.schema_id ); OPEN c1; FETCH NEXT FROM c1 INTO @table_name; WHILE @@FETCH_STATUS = 0 BEGIN SET @table_name = REPLACE(@table_name, '[',''); SET @table_name = REPLACE(@table_name, ']',''); -- make sure the object exists before calling sp_spacedused IF EXISTS(SELECT OBJECT_ID FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(@table_name)) BEGIN INSERT INTO @temp_table EXEC sp_spaceused @table_name, false ; END FETCH NEXT FROM c1 INTO @table_name; END; CLOSE c1; DEALLOCATE c1; SELECT t1.* , t2.schemaname FROM @temp_table t1

Page 122 of 211

INNER JOIN @tab1 t2 ON (t1.tablename = t2.tablename ) ORDER BY schemaname,tablename; END try BEGIN catch SELECT -100 AS l1 , ERROR_NUMBER() AS tablename , ERROR_SEVERITY() AS row_count , ERROR_STATE() AS reserved , ERROR_MESSAGE() AS data , 1 AS index_size, 1 AS unused, 1 AS schemaname END catch

Comments Issue 140: FILEPROPERTY - method of calculating disk space per DB. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 21-Feb-11

G(0)

Description
ILEPROPERTY Another option is to use the SpaceUsed property of the FILEPROPERTY function which will tell us how much space is used and then we can calculate free space based on the current size and what is being used. USE Test5 GO SELECT DB_NAME() AS DbName, name AS FileName, size/128.0 AS CurrentSizeMB, size/128.0 - CAST(FILEPROPERTY(name, 'SpaceUsed') AS INT)/128.0 AS FreeSpaceMB FROM sys.database_files;

Comments

Page 123 of 211

Issue 141: Get VLF count Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 23-Feb-11 Transaction log related queries

G(0)

Description
-- ============================================= -- Description: Gets vlf counts -- ============================================= CREATE PROCEDURE [dbo].[dba_InsertVLFS] AS BEGIN SET NOCOUNT ON; CREATE TABLE #VLFS (fileid int,filesize bigint,startoffset bigint,fseqno bigint,status int,parity int,createlsn varchar(1000)) CREATE TABLE #Results ([SQL Instance Name] nvarchar(500),[Database] nvarchar(500),[VLF COUNT] INT, [Status] INT) exec master.dbo.sp_msforeachdb @command1 = 'USE ? INSERT INTO #VLFS EXEC(''DBCC LOGINFO WITH TABLERESULTS'')', @command2 = 'insert into #Results SELECT @@SERVERNAME,''?'', count(*), SUM(status) from #vlfs', @command3 = 'truncate table #vlfs' SELECT * FROM #results INSERT INTO Admin_log.dbo.VLF_LOG (DB, VLFs, InUse) SELECT [Database] DB, [VLF COUNT] VLFs, Status/2 FROM #Results WHERE [Database] = 'Ecards'

DROP TABLE #vlfs DROP TABLE #Results END

Comments

Page 124 of 211

Issue 142: sys.dm_db_session_space_usage - to calculate tempdev files usage Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 24-Feb-11 tempdb space related

G(0)

Description
select * from sys.dm_db_session_space_usage where session_id >50 order by user_objects_alloc_page_count + internal_objects_alloc_page_count desc;

Comments

Page 125 of 211

Issue 143: Planned Failover - Log Shipping Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-Feb-11 Log Shipping

G(0)

Description
1) Stop and disable the primary server transaction log backup job. 2) Manually copy all transacions-log backups that have not been copied from primary server backup folder to the secondary server folder. 3) Then restore each transaction log in sequence to the secondary server. A different option is to execute the log shipping copy and restore jobs to restore the remainder of the transaction logs. Then use log shipping monitoring tool or report to varify that entire set of transaction- log backups have been copied and restored on the secondary server. 4) stop and disable the secondary server's copy and restore jobs. 5) execute the sync Secondary Server Access information job and then disable it 6) back up the active portion of transaction log from the primary to the secondary server with norecovery: use Master; backup log <database_name> to disk = 'C:\PrimaryBackupDir\<database_name>.trn' with norecovery this accomplishes two goals: A. Backs up the active transaction log from primary server and restore it into the secondary server to synchronize the secondary database. B.Changes the old primary server database to norecovery mode to allow transaction logs from the new primary server to be applied without initializing the database by restore, as the log chain would not have been broken. 7) on the secondary server, restore the active portion of transaction log and then recover the database Restore log <databaseName> from disk = 'C:\secondaryDirectory\database_name.trn' with norecovery 8) if the active transaction log is not not accessible, the database can be recovered without it: restore database <database_name> with recovery 9) on the primary server, execute the resolve logins job to synchronize the logins. The secondary server's database becomes the primary server's database and will start to accept data modifications. 10) redirect all applications to the new priamry server. 11) configure log shipping from the new primary server to the secondary server. The Secondary server(the former primary server) is already in norecovery mode. During log shipping configuration, in the secondary database settings dialog box, choose "No, the secondary database is initialized" 12) when you finish configuring log shipping, the new primary server will be executing the transaction-log backup job, and the secondary server will be copying and restoring the transaction log files. Set up and enable all SQL jobs that were synchronizing from the old primary server(for example, to syncchronize the logins and the database users to the old primary server).

Comments

Page 126 of 211

Issue 144: Different trace Flag.. Category Status Priority Attachments (1) Category Active (1) High Assigned To Due Date Opened By Opened Date 25-Feb-11 Sql Server Internal concept

G(0)

Description Comments

Page 127 of 211

Issue 145: How to: Manually Uninstall a SQL Server 2005 Failover Cluster Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 28-Feb-11 Cluster

G(0)

Description

Consider the following important points before you uninstall a Microsoft SQL Server 2005 failover cluster: On a computer running SQL Server 2005 along with previous SQL Server versions, Enterprise Manager and other programs that depend on SQL-DMO may be disabled. This may occur in the following situations: Side-by-side installations of SQL Server 2005, SQL Server 2000, and SQL Server 7.0, where any of the versions is uninstalled. Side-by-side installations of SQL Server 2000 with SQL Server 2005, where SQL Server 2000 is installed after SQL Server 2005. This issue is due to removal of the registration for the SQL Server 2005 SQL-DMO COM library. To re-enable Enterprise Manager and other programs with SQL-DMO dependencies, register SQL-DMO by running regsvr32.exe sqldmo.dll from a command prompt. For more information, see Troubleshooting an Installation of the SQL Server Database Engine. If SQL Native Client is uninstalled by accident, SQL Server resources will fail to start. To reinstall SQL Native Client, run the SQL Server 2005 Setup program to install SQL Server 2005 prerequisites. If you uninstall a failover cluster that has more than one SQL IP cluster resource, you must remove the additional SQL IP resources using cluster administrator. javascript:void(0)To uninstall a SQL Server 2005 failover cluster after a failed uninstallation using the SQL Server Setup program 1. Backup the existing registry on each node before removing SQL Server 2005. 2. Using the Registry Editor utility (regedit.exe) locate the registry key HKLM\Software \Microsoft\Microsoft SQL Server\<instid>\Setup, where <instid> represents the specific instance of SQL Server 2005 being uninstalled (for example, MSSQL.1 for the first instance, MSSQL.2 for the second instance, etc.). In this key set SqlCluster=0. This will uncluster the clustered instance of SQL Server 2005. 1. Caution Incorrectly editing the registry can cause serious problems that may require you to reinstall your operating system. Microsoft cannot guarantee that problems resulting from editing the registry incorrectly can be resolved. Before editing the registry, back up the registry and any valuable data. 3. Ensure that the shared disk is available to the node being removed. 4. Launch Add or Remove Programs in Control Panel. 5. Select the SQL Server 2005 instance to uninstall, and then click Remove. This will launch the SQL Server 2005 Installation Wizard. 6. On the Component Selection page, select Remove SQL Server 2005 instance components and then click the instance name and common components to uninstall. To continue, click Next. 7. On the Remote Login Information page, provide the password for the administrator account on all nodes of the clustered instance. To continue, click Next.
Page 128 of 211

8. On the Confirmation page, verify the selections for SQL Server components that will be removed. To continue with the uninstallation process, click Finish. 9. The SQL Server 2005 Installation Wizard will remove SQL Server 2005 components from your computer. If Setup requires access to the SQL Server 2005 installation media, you will be prompted to insert the CD or DVD into the CD or DVD drive. The CD or DVD used to uninstall SQL Server must have the same build number as the SQL Server instance you are trying to uninstall. For network installations, Setup must have access to the network build folder. 10. The SQL Server 2005 System Configuration Checker will scan your computer's existing configuration. On the Welcome page, click Next. After the System Configuration Checker finishes its scan, click Next to continue. 11. The Setup Progress page will display status as it removes SQL Server 2005 from your computer. On the Completing the Microsoft SQL Server Installation Wizard page, you can view the Setup summary log by clicking the link provided on this page. To exit the SQL Server Installation Wizard, click Finish. 1. Note Do not attempt to uninstall MSXML or SQLXML; they will be automatically removed when all dependent components are uninstalled. 12. Move the shared disk to the next node to be uninstalled, and on this node, repeat steps 1 - 11. Continue to backup the registry and any other important data on each node, edit the registry to uncluster the cluster, move the shared disk so that it is available to the node being removed, and then use Add or Remove Programs to remove SQL Server 2005 from that node. 13. Repeat this move-and-uninstall process for each remaining node.
Comments [Version: 2/28/2011 9:39:54 PM ] http://msdn.microsoft.com/en-us/library/ms180973(SQL.90).aspx Issue 146: How to Resolve missing MSI or MSP packages during SQL Server Service Packs, Hotfix or Cumulative Updates Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 28-Feb-11 Installation and Service Pack upgra

G(0)

Description
http://support.microsoft.com/kb/2015100

Comments [Version: 2/28/2011 10:48:30 PM ] http://support.microsoft.com/kb/2015100

Page 129 of 211

Issue 147: Cluster Commands from Windows DOS prompt. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 09-Mar-11 Cluster

G(0)

Description

To find a specific SQL Server network resource name : cluster.exe resource In this example, you can use the following commands to create a list of possible owners for each SQL Network Name resource: cluster.exe resource SQL Network Name (SQLVS1) /listofowners > c:\SQLVS1 _list_of_owners.txt cluster.exe resource SQL Network Name (SQLVS2) /listofowners > c:\SQLVS2 _list_of_owners.txt

Comments Issue 148: CLUSTER.EXE YourClusterName LOG /GEN /COPY:"C:\Temp\cluster.log" Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 10-Mar-11 Cluster

G(0)

Description
in windows server 2008: CLUSTER.EXE YourClusterName LOG /GEN /COPY:"C:\Temp\cluster.log"

Comments

Page 130 of 211

Issue 149: Sql Server Resource Fails to come online on Cluster with Error Error Locating Server/Instance Specified [xFFFFFFFF] Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 11-Mar-11 Cluster

G(0)

Description
Sql Server Resource Fails to come online on Cluster with Error Error Locating Server/Instance Specified [xFFFFFFFF] As mentioned in my previous posts if the sql server fails to come online we need to start troubleshooting by looking at the sql server error log. So we checked the sql server error log and found that sql server was started successfully and there was no error mentioned in the sql server error log. We checked the cluster.log located in the C:\Windows\Cluster folder and found the following error ERR SQL Server <SQL Server (SHHRDBCL2)>: [sqsrvres] ODBC sqldriverconnect failed ERR SQL Server <SQL Server (SHHRDBCL2)>: [sqsrvres] checkODBCConnectError: sqlstate = 08001; native error = ffffffff; message = [Microsoft][SQL Native Client]SQL Network Interfaces: Error Locating Server/Instance Specified [xFFFFFFFF]. ERR SQL Server <SQL Server (SHHRDBCL2)>: [sqsrvres] ODBC sqldriverconnect failed ERR SQL Server <SQL Server (SHHRDBCL2)>: [sqsrvres] checkODBCConnectError: sqlstate = HYT00; native error = 0; message = [Microsoft][SQL Native Client]Login timeout expired ERR SQL Server <SQL Server (SHHRDBCL2)>: [sqsrvres] ODBC sqldriverconnect failed ERR SQL Server <SQL Server (SHHRDBCL2)>: [sqsrvres] checkODBCConnectError: sqlstate = 08001; native error = ffffffff; message = [Microsoft][SQL Native Client]An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. As seen from the above Error message Error Locating Server/Instance Specified [xFFFFFFFF], the cluster service was not able to locate the instance of the sql server instance. We tried to connect to the sql server instance using management studio but it failed with the same error message as above. CAUSE ===== So we checked Sql browser service and found that the sql browser service was stopped and was in manual mode. Sql Browser is the one which is responsible to route all the incoming connections for the sql server to their appropriate TCP port on which the sql server is listening. Sql browser service itself listen on port 1434 on UDP protocol. So whenever a client attempts to connect to the named instance of sql server, it will first try to connect to the Sql browser service which runs on port 1434 and then routes to the appropriate port on which sql server instance is listening. However the above explanation does not hold true for default instance of the sql server which runs on port 1433 and hence the client does not require sql browser to route its connection but instead connects directly to port. RESOLUTION ========= So we started the sql browser service and changed it state to Automatic from manual. We observed that sql

Page 131 of 211

server came online fine without any error on node 2 without any error. However some customers do not want the sql browser service to be started for security reasons so in that case for the cluster service to connect to the sql server it should have alias create for the Cluster service to know the port on which the sql is running on. So we need to create a TCP/IP alias on both nodes of the server with Alias Name: SHHRDBCL2\SHHRDBCL2 Server: SHHRDBCL2\SHHRDBCL2 TCP Port: <tcp-port> Once the alias was created the sql server resource were coming online on both nodes of the cluster with sql browser service stopped.

Comments [Version: 3/11/2011 1:58:46 AM ] From errorlog file if sql server services comes online where as in cluster log the services are not coming online..

Page 132 of 211

Issue 150: Unable to failover a Named instance of SQL server 2005 in cluster or unable to bring a Named Instance of SQL server 2005 Online Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 11-Mar-11 Cluster

G(0)

Description
The problem is that we have a Named instance of SQL Server 2005 in a 2 node cluster. While trying to bring the SQL Services online we get these error messages in the Application Event Log. Application Event Log: Event Type: Error Event Source: MSSQL$SQL2k5 Event Category: (3) Event ID: 19019 Date: 7/17/2009 Time: 7:12:00 AM User: N/A Computer: BLRS2R17-3 Description: [sqsrvres] ODBC sqldriverconnect failed Event Type: Error Event Source: MSSQL$SQL2k5 Event Category: (3) Event ID: 19019 Date: 7/17/2009 Time: 7:12:00 AM User: N/A Computer: BLRS2R17-3 Description: [sqsrvres] checkODBCConnectError: sqlstate = 08001; native error = ffffffff; message = [Microsoft][SQL Native Client]SQL Network Interfaces: Error Locating Server/Instance Specified [xFFFFFFFF]. Event Type: Error Event Source: MSSQL$SQL2k5 Event Category: (3) Event ID: 19019 Date: 7/17/2009 Time: 7:12:00 AM User: N/A Computer: BLRS2R17-3 Description: [sqsrvres] ODBC sqldriverconnect failed Event Type: Error Event Source: MSSQL$SQL2k5 Event Category: (3) Event ID: 19019 Date: 7/17/2009 Time: 7:12:00 AM User: N/A Computer: BLRS2R17-3

Page 133 of 211

Description: [sqsrvres] checkODBCConnectError: sqlstate = HYT00; native error = 0; message = [Microsoft][SQL Native Client]Login timeout expired

Cause: The cluster service is not able to Connect with Clustered Named instance of SQL Server. SQL Browser even though running is not actually listening for requests. Note: The SQL Server Browser program runs as a Windows service. SQL Server Browser listens for incoming requests for Microsoft SQL Server resources and provides information about SQL Server instances installed on the computer. Resolution: We started the SQL Server Browser Service with the -c parameter from command prompt it gave us the below response. F:\Program Files (x86)\Microsoft SQL Server\90\Shared>sqlbrowser -c SQLBrowser: starting up in console mode We checked the same in a working cluster and found that when a browser is started it should have been like below, F:\Program Files (x86)\Microsoft SQL Server\90\Shared>sqlbrowser -c SQLBrowser: starting up in console mode SQLBrowser: starting up SSRP redirection service SQLBrowser is successfully listening on 0.0.0.0[1434] [3728]: Waiting for next request... [3728]: Received request... [3768]: Waiting for next request... [0532]: Waiting for next request... [4612]: Waiting for next request... [3728]: Waiting for next request... [3768]: Received request... [3768]: Waiting for next request... We found that the SsrpListener key was 0 Path Of The Registry SsrpListener Key : HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Microsoft SQL Server\90\SQL Browser (x64 Machines) HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\90\SQL Browser (x86 Machines) Note: The SsrpListener registry value allows or disallows the SQL Browser to expose Engine instance discovery information, So if the value is 0 it disallows the SQL Browser to expose Engine instance discovery. After we changed value to 1 and restarted the browser service we were getting the response as expected. We stopped the browser service from the command prompt and then started it from services console and then we were able to bring the SQL Server Services online. Another Workaround for this issue is to manually create a TCP alias with port number in all the nodes. In that case we need to make sure that SQL is not set to work with dynamic ports.

More Information: In x64 bit machines you may get into another issue. Once after you change the SsrpListener value to 1 and then when you try to start the browser service through command prompt you may get this response. C:\Program Files (x86)\Microsoft SQL Server\90\Shared>sqlbrowser -c SQLBrowser: starting up in console mode SQLBrowser: starting up SSRP redirection service SQLBrowser is successfully listening on 0.0.0.0[1434] SQLBrowser: failed starting SSRP redirection services -- shutting down.

Page 134 of 211

This is caused by the entry in the Wow6432Node registry pertaining to this installation eventhough this was a 64 bit installation. This happens only in x64 machines. You can remove the checkpoint and then delete this key from both the nodes and then add the checkpoint back. HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Microsoft SQL Server\MSSQL.2\MSSQLServer If registry checkpoint is not removed properly before deleting this key you may get this error message continously in the Event Logs. Cluster service could not write to a file (C:\DOCUME~1\SVC~1.WES\LOCALS~1\Temp\CLS2AF.tmp). The disk may be low on disk space, or some other serious condition exists.

Comments

Page 135 of 211

Issue 151: Moving System Databases - SQL Server 2005 Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 14-Mar-11 Installation and Service Pack upgra

G(0)

Description

Updated: 17 November 2008 This topic describes how to move system databases in SQL Server 2005. Moving system databases may be useful in the following situations: Failure recovery. For example, the database is in suspect mode or has shut down because of a hardware failure. Planned relocation. Relocation for scheduled disk maintenance. The following procedures apply to moving database files within the same instance of SQL Server. To move a database to another instance of SQL Server or to another server, use the backup and restore or detach and attach operations. The procedures in this topic require the logical name of the database files. To obtain the name, query the name column in the sys.master_files catalog view. Important:

If you move a system database and subsequently rebuild the master database, you must move the system database again because the rebuild operation installs all system databases to their default location. For more information about rebuilding the master database, see "Rebuilding System Databases, Rebuilding the Registry" in How to: Install SQL Server 2005 from the Command Prompt. javascript:void(0)Planned Relocation and Scheduled Disk Maintenance Procedure To move a system database data or log file as part of a planned relocation or scheduled maintenance operation, follow these steps. This procedure applies to all system databases except the master and Resource databases. 1. For each file to be moved, run the following statement. 1. 2. Copy

3. ALTER DATABASE database_name MODIFY FILE ( NAME = logical_name , FILENAME = 'new_path\os_file_name' )

2. Stop the instance of SQL Server or shut down the system to perform maintenance. For more information, see Stopping Services. 3. Move the file or files to the new location. 4. Restart the instance of SQL Server or the server. For more information, see Starting and Restarting Services. 5. Verify the file change by running the following query. 1. 2. Copy
3. SELECT name, physical_name AS CurrentLocation, state_desc 4. FROM sys.master_files

Page 136 of 211

5. WHERE database_id = DB_ID(N'<database_name>');

If the msdb database is moved and the instance of SQL Server is configured for Database Mail, complete these additional steps. 1. Verify that Service Broker is enabled for the msdb database by running the following query. 1. 2. Copy
3. SELECT is_broker_enabled 4. FROM sys.databases 5. WHERE name = N'msdb';

6. For more information about enabling Service Broker, see ALTER DATABASE (Transact-SQL). 2. Verify that Database Mail is working by sending a test mail. For more information, see Troubleshooting Database Mail. javascript:void(0)Failure Recovery Procedure If a file must be moved because of a hardware failure, follow these steps to relocate the file to a new location. This procedure applies to all system databases except the master and Resource databases. Important:

If the database cannot be started--that is, it is in suspect mode or in an unrecovered state--only members of the sysadmin fixed role can move the file. 1. Stop the instance of SQL Server if it is started. 2. Start the instance of SQL Server in master-only recovery mode by entering one of the following commands at the command prompt. The parameters specified in these commands are case sensitive. The commands fail when the parameters are not specified as shown. For the default (MSSQLSERVER) instance, run the following command: 1. 2. Copy
3. NET START MSSQLSERVER /f /T3608

For a named instance, run the following command: 1. 2. Copy

3. NET START MSSQL$instancename /f /T3608

1. For more information, see How to: Start an Instance of SQL Server (net Commands). 1. For each file to be moved, use sqlcmd commands or SQL Server Management Studio to run the following statement. 1. 2. Copy
3. ALTER DATABASE database_name MODIFY FILE( NAME = logical_name , FILENAME = 'new_path\os_file_name' )

4. For more information about using the sqlcmd utility, see Using the sqlcmd Utility. 2. Exit the sqlcmd utility or SQL Server Management Studio. 3. Stop the instance of SQL Server. For example, run NET STOP MSSQLSERVER. 4. Move the file or files to the new location. 5. Restart the instance of SQL Server. For example, run NET START MSSQLSERVER. 6. Verify the file change by running the following query. 1.
Page 137 of 211

2. Copy

3. SELECT name, physical_name AS CurrentLocation, state_desc 4. FROM sys.master_files 5. WHERE database_id = DB_ID(N'<database_name>');

javascript:void(0)Moving the master and Resource Databases The Resource database depends on the location of the master database. The Resource data and log files must reside together and must be in the same location as the master data file (master.mdf). Therefore, if you move the master database, you must also move the Resource database to the same location as the master data file. Do not put the Resource database in either compressed or encrypted NTFS file system folders. Doing so will hinder performance and prevent upgrades. To move the master and Resource databases, follow these steps. 1. From the Start menu, point to All Programs, point to Microsoft SQL Server 2005, point to Configuration Tools, and then click SQL Server Configuration Manager. 2. In the SQL Server 2005 Services node, right-click the instance of SQL Server (for example, SQL Server (MSSQLSERVER)) and choose Properties. 3. In the SQL Server (instance_name) Properties dialog box, click the Advanced tab. 4. Edit the Startup Parameters values to point to the planned location for the master database data and log files, and click OK. Moving the error log file is optional. 5. The parameter value for the data file must follow the -d parameter and the value for the log file must follow the -l parameter. The following example shows the parameter values for the default location of the master data and log files. 1. 2. Copy
3. -dC:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA \master.mdf;-eC:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\LOG \ERRORLOG;-lC:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA \mastlog.ldf 4. If the planned relocation for the master data and log files is E:\SQLData, the

parameter values would be changed as follows: 5. 6. Copy

7. -dE:\SQLData\master.mdf;-eC:\Program Files\Microsoft SQL Server \MSSQL.1\MSSQL\LOG\ERRORLOG;-lE:\SQLData\mastlog.ldf

6. Stop the instance of SQL Server by right-clicking the instance name and choosing Stop. 7. Move the master.mdf and mastlog.ldf files to the new location. 8. Start the instance of SQL Server in master-only recovery mode by entering one of the following commands at the command prompt. The parameters specified in these commands are case sensitive. The commands fail when the parameters are not specified as shown. For the default (MSSQLSERVER) instance, run the following command. 1. 2. Copy
3. NET START MSSQLSERVER /f /T3608

For a named instance, run the following command. 1. 2. Copy

3. NET START MSSQL$instancename /f /T3608

1. For more information, see How to: Start an Instance of SQL Server (net Commands). 1. Using sqlcmd commands or SQL Server Management Studio, run the following statements. Change the FILENAME path to match the new location of the master data file.

Page 138 of 211

Do not change the name of the database or the file names. 1. 2. Copy

3. ALTER DATABASE mssqlsystemresource 4. MODIFY FILE (NAME=data, FILENAME= 'new_path_of_master \mssqlsystemresource.mdf'); 5. GO 6. ALTER DATABASE mssqlsystemresource 7. MODIFY FILE (NAME=log, FILENAME= 'new_path_of_master \mssqlsystemresource.ldf'); 8. GO

2. Move the mssqlsystemresource.mdf and mssqlsystemresource.ldf files to the new location. 3. Set the Resource database to read-only by running the following statement. 1. 2. Copy
3. ALTER DATABASE mssqlsystemresource SET READ_ONLY;

4. Exit the sqlcmd utility or SQL Server Management Studio. 5. Stop the instance of SQL Server. 6. Restart the instance of SQL Server. 7. Verify the file change for the master database by running the following query. The Resource database metadata cannot be viewed by using the system catalog views or system tables. 1. 2. Copy
3. 4. 5. 6. SELECT name, physical_name AS CurrentLocation, state_desc FROM sys.master_files WHERE database_id = DB_ID('master'); GO

javascript:void(0)Examples

A. Moving the tempdb database


The following example moves the tempdb data and log files to a new location as part of a planned relocation. Note:

Because tempdb is re-created each time the instance of SQL Server is started, you do not have to physically move the data and log files. The files are created in the new location when the service is restarted in step 3. Until the service is restarted, tempdb continues to use the data and log files in existing location. 1. Determine the logical file names of the tempdb database and their current location on the disk. 1. 2. Copy
SELECT name, physical_name AS CurrentLocation FROM sys.master_files WHERE database_id = DB_ID(N'tempdb'); GO Change the location of each file by using ALTER DATABASE. 3. 4. 5. 6.

2.

1. 2. Copy

3. USE master; 4. GO 5. ALTER DATABASE tempdb


Page 139 of 211

6. MODIFY FILE (NAME = tempdev, FILENAME = 'E:\SQLData\tempdb.mdf'); 7. GO 8. ALTER DATABASE tempdb 9. MODIFY FILE (NAME = templog, FILENAME = 'F:\SQLLog\templog.ldf'); 10. GO

3. Stop and restart the instance of SQL Server. 4. Verify the file change. 1. 2. Copy

3. SELECT name, physical_name AS CurrentLocation, state_desc 4. FROM sys.master_files 5. WHERE database_id = DB_ID(N'tempdb');

5. Delete the tempdb.mdf and templog.ldf files from the original location.
Comments [Version: 3/14/2011 10:25:26 PM ] http://msdn.microsoft.com/en-us/library/ms345408(v=SQL.90).aspx

Page 140 of 211

Issue 152: Moving System Databases - SQl Server 2008 Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 14-Mar-11 Installation and Service Pack upgra

G(0)

Description

This topic describes how to move system databases in SQL Server. Moving system databases may be useful in the following situations: Failure recovery. For example, the database is in suspect mode or has shut down because of a hardware failure. Planned relocation. Relocation for scheduled disk maintenance. The following procedures apply to moving database files within the same instance of SQL Server. To move a database to another instance of SQL Server or to another server, use the backup and restore or detach and attach operations. The procedures in this topic require the logical name of the database files. To obtain the name, query the name column in the sys.master_files catalog view. Important

If you move a system database and later rebuild the master database, you must move the system database again because the rebuild operation installs all system databases to their default location. For more information about rebuilding the master database, see "Rebuilding System Databases, Rebuilding the Registry" in How to: Install SQL Server 2008 R2 from the Command Prompt. javascript:void(0)Planned Relocation and Scheduled Disk Maintenance Procedure To move a system database data or log file as part of a planned relocation or scheduled maintenance operation, follow these steps. This procedure applies to all system databases except the master and Resource databases. 1. For each file to be moved, run the following statement. 1. 2. Copy

3. ALTER DATABASE database_name MODIFY FILE ( NAME = logical_name , FILENAME = 'new_path\os_file_name' )

2. Stop the instance of SQL Server or shut down the system to perform maintenance. For more information, see Stopping Services. 3. Move the file or files to the new location. 4. Restart the instance of SQL Server or the server. For more information, see Starting and Restarting Services. 5. Verify the file change by running the following query. 1. 2. Copy
3. SELECT name, physical_name AS CurrentLocation, state_desc 4. FROM sys.master_files 5. WHERE database_id = DB_ID(N'<database_name>');

If the msdb database is moved and the instance of SQL Server is configured for Database
Page 141 of 211

Mail, complete these additional steps. 1. Verify that Service Broker is enabled for the msdb database by running the following query. 1. 2. Copy
3. SELECT is_broker_enabled 4. FROM sys.databases 5. WHERE name = N'msdb';

6. For more information about enabling Service Broker, see ALTER DATABASE (Transact-SQL). 2. Verify that Database Mail is working by sending a test mail. For more information, see Troubleshooting Database Mail. javascript:void(0)Failure Recovery Procedure If a file must be moved because of a hardware failure, follow these steps to relocate the file to a new location. This procedure applies to all system databases except the master and Resource databases. Important

If the database cannot be started, that is it is in suspect mode or in an unrecovered state, only members of the sysadmin fixed role can move the file. 1. Stop the instance of SQL Server if it is started. 2. Start the instance of SQL Server in master-only recovery mode by entering one of the following commands at the command prompt. The parameters specified in these commands are case sensitive. The commands fail when the parameters are not specified as shown. For the default (MSSQLSERVER) instance, run the following command: 1. 2. Copy
3. NET START MSSQLSERVER /f /T3608

For a named instance, run the following command: 1. 2. Copy

3. NET START MSSQL$instancename /f /T3608

1. For more information, see How to: Start an Instance of SQL Server (net Commands). 1. For each file to be moved, use sqlcmd commands or SQL Server Management Studio to run the following statement. 1. 2. Copy
3. ALTER DATABASE database_name MODIFY FILE( NAME = logical_name , FILENAME = 'new_path\os_file_name' )

4. For more information about using the sqlcmd utility, see Using the sqlcmd Utility. 2. Exit the sqlcmd utility or SQL Server Management Studio. 3. Stop the instance of SQL Server. For example, run NET STOP MSSQLSERVER. 4. Move the file or files to the new location. 5. Restart the instance of SQL Server. For example, run NET START MSSQLSERVER. 6. Verify the file change by running the following query. 1. 2. Copy
3. SELECT name, physical_name AS CurrentLocation, state_desc

Page 142 of 211

4. FROM sys.master_files 5. WHERE database_id = DB_ID(N'<database_name>');

javascript:void(0)Moving the master Database To move the master database, follow these steps. 1. From the Start menu, point to All Programs, point to Microsoft SQL Server, point to Configuration Tools, and then click SQL Server Configuration Manager. 2. In the SQL Server Services node, right-click the instance of SQL Server (for example, SQL Server (MSSQLSERVER)) and choose Properties. 3. In the SQL Server (instance_name) Properties dialog box, click the Advanced tab. 4. Edit the Startup Parameters values to point to the planned location for the master database data and log files, and click OK. Moving the error log file is optional. 1. The parameter value for the data file must follow the -d parameter and the value for the log file must follow the -l parameter. The following example shows the parameter values for the default location of the master data and log files. 2. 3. Copy
4. -dC:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER \MSSQL\DATA\ 5. master.mdf;-eC:\Program Files\Microsoft SQL Server\MSSQL10_ 50.MSSQLSERVER\MSSQL\ 6. LOG\ERRORLOG;-lC:\Program Files\Microsoft SQL Server\MSSQL10_ 50.MSSQLSERVER\MSSQL\ 7. DATA\mastlog.ldf

8. If the planned relocation for the master data and log files is E:\SQLData, the parameter values would be changed as follows: 9. 10. Copy

11. -dE:\SQLData\master.mdf;-eC:\Program Files\Microsoft SQL Server \MSSQL10_50.MSSQLSERVER\MSSQL\LOG\ERRORLOG;-lE:\SQLData\mastlog.ldf

5. Stop the instance of SQL Server by right-clicking the instance name and choosing Stop. 6. Move the master.mdf and mastlog.ldf files to the new location. 7. Restart the instance of SQL Server. 8. Verify the file change for the master database by running the following query. 1. 2. Copy
3. 4. 5. 6. SELECT name, physical_name AS CurrentLocation, state_desc FROM sys.master_files WHERE database_id = DB_ID('master'); GO

javascript:void(0)Moving the Resource Database The location of the Resource database is <drive>:\Program Files\Microsoft SQL Server \MSSQL10_50.<instance_name>\MSSQL\Binn\. The database cannot be moved. javascript:void(0)Examples

A. Moving the tempdb database


The following example moves the tempdb data and log files to a new location as part of a planned relocation. Note

Because tempdb is re-created each time the instance of SQL Server is started, you do not have to physically move the data and log files. The files are created in the new location when the service is restarted in step 3. Until the service is restarted, tempdb continues to use the data
Page 143 of 211

and log files in existing location. 1. Determine the logical file names of the tempdb database and their current location on the disk. 1. 2. Copy
3. 4. 5. 6. SELECT name, physical_name AS CurrentLocation FROM sys.master_files WHERE database_id = DB_ID(N'tempdb'); GO

2. Change the location of each file by using ALTER DATABASE. 1. 2. Copy

3. USE master; 4. GO 5. ALTER DATABASE tempdb 6. MODIFY FILE (NAME = tempdev, FILENAME = 'E:\SQLData\tempdb.mdf'); 7. GO 8. ALTER DATABASE tempdb 9. MODIFY FILE (NAME = templog, FILENAME = 'F:\SQLLog\templog.ldf'); 10. GO

3. Stop and restart the instance of SQL Server. 4. Verify the file change. 1. 2. Copy

3. SELECT name, physical_name AS CurrentLocation, state_desc 4. FROM sys.master_files 5. WHERE database_id = DB_ID(N'tempdb');

5. Delete the tempdb.mdf and templog.ldf files from the original location.
Comments [Version: 3/14/2011 10:27:51 PM ] http://msdn.microsoft.com/en-us/library/ms345408(v=SQL.105).aspx Issue 153: database Mirroring Monitor (status page). Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 15-Mar-11 Mirroring

G(0)

Description Comments [Version: 3/15/2011 12:22:44 AM ] http://msdn.microsoft.com/en-us/library/ms365413.aspx.

Page 144 of 211

Issue 154: SQL SERVER 2008 Display Fragmentation Information of Data and Indexes of Database Table Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 07-Jun-11 Indexing

G(0)

Description

SELECT OBJECT_NAME(i.OBJECT_ID) AS TableName, i.name AS IndexName, indexstats.avg_fragmentation_in_percent FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'DETAILED') indexstats INNER JOIN sys.indexes i ON i.OBJECT_ID = indexstats.OBJECT_ID AND i.index_id = indexstats.index_id WHERE indexstats.avg_fragmentation_in_percent > 20
Comments Issue 155: To check query by logical Read/Logical Write/ expensive query Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 17-Jun-11 Performance Issue

G(0)

Description SELECT TOP 10 SUBSTRING(qt.TEXT, (qs.statement_start_offset/2)+1, ((CASE qs.statement_end_offset WHEN -1 THEN DATALENGTH(qt.TEXT) ELSE qs.statement_end_offset END - qs.statement_start_offset)/2)+1), qs.execution_count, qs.total_logical_reads, qs.last_logical_reads, qs.total_logical_writes, qs.last_logical_writes, qs.total_worker_time, qs.last_worker_time, qs.total_elapsed_time/1000000 total_elapsed_time_in_S, qs.last_elapsed_time/1000000 last_elapsed_time_in_S, qs.last_execution_time, qp.query_plan FROM sys.dm_exec_query_stats qs CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) qt CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp --ORDER BY qs.total_logical_reads DESC -- logical reads -- ORDER BY qs.total_logical_writes DESC -- logical writes ORDER BY qs.total_worker_time DESC -- CPU time Comments

Page 145 of 211

Issue 156: Running a Script from SQLCMD Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 17-Jun-11 SQLCMD -Script

G(0)

Description
Lesson 2: Running Transact-SQL Script Files by Using sqlcmd SQL Server 2008 R2 Other Versions You can use sqlcmd to run a Transact-SQL script file. A Transact-SQL script file is a text file that can contain a combination of Transact-SQL statements, sqlcmd commands, and scripting variables. To create a simple Transact-SQL script file by using Notepad, follow these steps: Click Start, point to All Programs, point to Accessories, and then click Notepad. Copy and paste the following Transact-SQL code into Notepad: USE AdventureWorks2008R2; GO SELECT p.FirstName + ' ' + p.LastName AS 'Employee Name', a.AddressLine1, a.AddressLine2 , a.City, a.PostalCode FROM Person.Person AS p INNER JOIN HumanResources.Employee AS e ON p.BusinessEntityID = e.BusinessEntityID INNER JOIN Person.BusinessEntityAddress bea ON bea.BusinessEntityID = e.BusinessEntityID INNER JOIN Person.Address AS a ON a.AddressID = bea.AddressID; GO Save the file as myScript.sql in the C drive. To run the script file Open a command prompt window. In the Command Prompt window, type: sqlcmd -S myServer\instanceName -i C:\myScript.sql Press ENTER. A list of Adventure Works employee names and addresses is written to the command prompt window. To save this output to a text file Open a command prompt window. In the Command Prompt window, type: sqlcmd -S myServer\instanceName -i C:\myScript.sql -o C: \EmpAdds.txt Press ENTER.

Comments

Page 146 of 211

Issue 157: The ultimate guide to the datetime datatypes Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 19-Jun-11 DATETIME DataType

G(1)

Description Comments

Issue 158: Fix: "Difference of two datetime columns caused overflow at runtime" in Performance Dashboard. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 19-Jun-11 Performance dashboard report

G(0)

Description
Mar 4, 2008 Fix: "Difference of two datetime columns caused overflow at runtime" in Performance Dashboard. Error: Difference of two datetime columns caused overflow at runtime Solution: to modify msdb.MS_PerfDashboard.usp_Main_GetSessionInfo sum(convert(bigint, datediff(ms, login_time, getdate()))) - sum(convert(bigint, s.total_elapsed_time)) as idle_connection_time, to: sum(convert(bigint, CAST ( DATEDIFF ( minute, login_time, getdate()) AS BIGINT)*60000 + DATEDIFF ( millisecond, DATEADD ( minute, DATEDIFF ( minute, login_time, getdate() ), login_time ),getdate() ))) sum(convert(bigint, s.total_elapsed_time)) as idle_connection_time,

Comments
Issue 159: Quickest way to find the recovery model of any database Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 19-Jun-11 Database Property

G(0)

Description
Select recovery_model_desc from sys.databases Where name=AdventureWorks

Comments

Page 147 of 211

Issue 160: disable all foreign key constraint in one shot Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 20-Jun-11 Database Property

G(0)

Description
SET NOCOUNT ON SET ROWCOUNT 0 DECLARE @Count int DECLARE @String nvarchar (1000) DECLARE @ConstraintName varchar(128) DECLARE @TableName varchar(128) --Find all constraints and their respective tables from the sysobjects table and place into a temp table. --Primary Key and Unique Constraints via Unique Indexes are not disabled through this command --You should use the ALTER INDEX...DISABLE command in SQL Server 2005 SELECT name AS constraintname, object_name(parent_obj) AS tablename INTO #Const_Table FROM sysobjects s where xtype in ('F') SELECT @Count = Count(*) FROM #Const_Table --Setting the rowcount to one allows for one row from the temp table to be picked off at a time. --Used as an alternative to a cursor. SET ROWCOUNT 1 --Loop until all rows in temp table have been processed. WHILE @Count > 0 BEGIN --The rowcount of one ensures that only one tablename and constraint name is picked. SELECT @TableName = TableName, @ConstraintName = ConstraintName FROM #Const_Table --Build execution string to disable constraint. SET @String = 'ALTER TABLE ['+ @tablename + '] NOCHECK CONSTRAINT [' + @constraintname +']' --Execute the SQL exec sp_executesql @string --Remove this row from the temp table, since it has now been processed. DELETE FROM #Const_Table WHERE ConstraintName = @ConstraintName and TableName = @TableName SET @Count = @Count - 1 END -- Loop set rowcount 0

Comments

Page 148 of 211

Issue 161: Verbose setting in replication and SkipErrors 20598 Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 20-Jun-11 Replication Concept

G(0)

Description
-Subscriber [FFEMSCOMSQL01] -SubscriberDB [ODS] -Publisher [FFESQPROD01\PRODINSTANCE01] -Distributor [FFESQPROD01\PRODINSTANCE01] -DistributorSecurityMode 1 -Publication [ProdMemPub] -PublisherDB [Membership] -Continuous -Output F:\Temp\dist.txt -Outputverboselevel 2 -SkipErrors 20598

Comments Issue 162: Shrink or truncate Mirrored Database Log file in sql server Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 24-Jun-11 Mirroring

G(0)

Description

DECLARE @sql VARCHAR(MAX) SET @sql = SELECT @sql = @sql+ USE [' + name + '] BACKUP LOG [' + name + '] TO DISK = \\CLOUD\Root\Databases\ + name + _ + convert(varchar(8),getdate(),112) + _log.bak DBCC SHRINKFILE ( + name + _log, 1, TRUNCATEONLY) FROM sys.databases WHERE name not in (master, tempdb, model, msdb, pubs, Northwind, ReportServer$SQL2005, ReportServer$SQL2005TempDB) AND user_access_desc = MULTI_USER AND is_read_only = 0 AND state_desc = ONLINE PRINT @sql EXEC(@sql
Comments

Page 149 of 211

Issue 163: Shrinking T-log file of Mirrored database Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 24-Jun-11

G(0)

Description
we got a case , where Mirror database T-log file was consuming all space of disk. if the database is mirrored database, then you cannot shirnk as Mirrored database as these databases are un usable , we can not access through GUI or through CUI. so we have to shrink the T-log file of Principal database. To shrink the Principal database, first check dbcc loginfo. Dbcc loginfo has status column. if status is 2 for all VLF then you can not shrink,so we have to wait for its status from 2 to 0. if it is not happening then take backup of T-log files. Navigate the output of dbcc loginfo status column to the end of file. Check the status , if last vlf status show's 0, then shrinking of T-log will work.

Comments

Page 150 of 211

Issue 164: Steps to implement SSL in SQL Server Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 24-Jun-11 Encryption-SQL Server

G(0)

Description
To implement SSL the steps are : By default sql server services start with : 010-08-26 03:08:08.70 spid13s 2010-08-26 03:08:08.70 spid15s 2010-08-26 03:08:08.70 spid16s 2010-08-26 03:08:08.70 spid20s 2010-08-26 03:08:08.70 spid17s 2010-08-26 03:08:08.70 spid14s 2010-08-26 03:08:08.70 spid19s 2010-08-26 03:08:08.70 spid18s 2010-08-26 03:08:08.70 spid21s 2010-08-26 03:08:10.96 spid10s 2010-08-26 03:08:11.63 Server 2010-08-26 03:08:11.64 Server 2010-08-26 03:08:11.64 Server \SQLLocal\MSSQLSERVER ]. 2010-08-26 03:08:11.64 Server \sql\query ]. Starting up database 'msdb'. Starting up database 'ReportServer'. Starting up database 'CHA2'. Starting up database 'AdventureWorks'. Starting up database 'AdventureWorksDW2008R2'. Starting up database 'ReportServerTempDB'. Starting up database 'AdventureWorksDW'. Starting up database 'AdventureWorksLT2008R2'. Starting up database 'AdventureWorksLT'. Starting up database 'tempdb'. A self-generated certificate was successfully loaded for encryption. Server is listening on [ 'any' <ipv4> 1433]. Server local connection provider is ready to accept connection on [ \\.\pipe Server local connection provider is ready to accept connection on [ \\.\pipe

And in Sql Server Configuration Manager-- > Protocols for MSSQLSERVER the Certificate tab the Certificate will be blank.

In SQL Native Client 10.0 Configuration Check Trust Server Certificate is yes or not if no then check it yes.

Then create a Cedrtificate with makecert command like

makecert -r -pe -n "CN= <Virtual Server name in case of cluster or physical server name in case of physical box >" -b 01/06/2011 -e 01/01/2036 -eku 1.3.6.1.5.5.7.3.1 -ss my -sr localMachine -sky exchange -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12 example: makecert -r -pe -n "CN= BLR1LS393493.savvis.ad.savvis.net" -b 01/06/2011 -e 01/01/2036 -eku 1.3.6.1.5.5.7.3.1 -ss my -sr localMachine -sky exchange -sp "Microsoft RSA SChannel Cryptographic Provider" sy 12 to run this command we have to install makecert.exe in the server.

Page 151 of 211

Now something will appear in the console Root Certificates>

After Certificate gets created go to sql server configuration Manager protocols for sql server and in Certificate tab-> created Certificate will appear in certificate drop down box. Now stop sql server services and restart it sql server error log will return -- >
2011-06-13 09:09:25.840 spid7s FILESTREAM: effective level = 0, configured level = 0, file system access share name = 'MSSQLSERVER'. 2011-06-13 09:09:25.860 spid7s SQL Trace ID 1 was started by login "sa". 2011-06-13 09:09:25.880 spid7s Starting up database 'mssqlsystemresource'. 2011-06-13 09:09:25.940 spid7s The resource database build version is 10.50.1600. This is an informational message only. No user action is required. 2011-06-13 09:09:26.370 spid9s Starting up database 'model'. 2011-06-13 09:09:26.380 spid7s Server name is 'BLR1LS393493'. This is an informational message only. No user action is required. 2011-06-13 09:09:26.670 Server The certificate [Cert Hash(sha1) "E9DC92F678E47CC9168ECB389341EF01D10C8DE4"] was successfully loaded for encryption. 2011-06-13 09:09:26.800 spid9s Clearing tempdb database. 2011-06-13 09:09:26.810 Server Server is listening on [ 'any' <ipv4> 1433]. 2011-06-13 09:09:26.840 Server Server local connection provider is ready to accept connection on [ \\.\pipe\SQLLocal\MSSQLSERVER ]. 2011-06-13 09:09:26.840 Server Server named pipe provider is ready to accept conne

So in this way we can implement SSL on the SQL Server Level.

Comments

Page 152 of 211

Issue 165: Steps to implement Transparent data encryption. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 24-Jun-11 Encryption-SQL Server

G(0)

Description
TDE(Transparent data encryption) is for data in case of theft of the data file and the backup file.

USE master; GO CREATE MASTER KEY ENCRYPTION BY PASSWORD = '<UseStrongPasswordHere>'; go CREATE CERTIFICATE MyServerCert WITH SUBJECT = 'My DEK Certificate' go To encrypt a user database a database key is required so,

USE AdventureWorks GO CREATE DATABASE ENCRYPTION KEY WITH ALGORITHM = AES_128 ENCRYPTION BY SERVER CERTIFICATE MyServerCert GO With the database key created, the database can be encrypted or decrypted using either an alter command or Management Studios Database Properties -> option page: ALTER DATABASE AdventureWorks SET ENCRYPTION ON GO Restore an encrypted database with Transparent Data Encryption Step 1: Additional files that should be obtained in order to restore the database on another server USE master; GO BACKUP MASTER KEY TO FILE = '<Master Key File>.key' ENCRYPTION BY PASSWORD = 'The backup password for the master key!' GO BACKUP CERTIFICATE MyServerCert TO FILE = '<Certificate File>.cer' WITH PRIVATE KEY ( FILE = '<Private Key File>.key', ENCRYPTION BY PASSWORD = 'The backup password for the private key!' ); GO Step 2: How to prepare the target server to restore the encrypted database

Page 153 of 211

USE master; GO RESTORE MASTER KEY FROM FILE = '<Master Key File>.key' DECRYPTION BY PASSWORD = 'The backup password for the master key!' ENCRYPTION BY PASSWORD = '<UseStrongPasswordHere>' GO OPEN MASTER KEY DECRYPTION BY PASSWORD = '<UseStrongPasswordHere>' GO ALTER MASTER KEY ADD ENCRYPTION BY SERVICE MASTER KEY GO CREATE CERTIFICATE MyServerCert FROM FILE = '<Certificate File>.cer' WITH PRIVATE KEY ( FILE = '<Private Key File>.key', DECRYPTION BY PASSWORD = 'The backup password for the private key!' ); GO

Comments

Page 154 of 211

Issue 166: Steps to implement Symetric key encryption.- part 1 Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 24-Jun-11 Encryption-SQL Server

G(0)

Description
In source server database: ----------------------------------------------------------------CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'enctTERstxi*^*&%'; alter MASTER KEY add ENCRYPTION BY SERVICE MASTER KEY CREATE CERTIFICATE enctstcert WITH SUBJECT = 'test cert'; CREATE SYMMETRIC KEY enctstKey WITH ALGORITHM = AES_256 ENCRYPTION BY CERTIFICATE enctstcert; OPEN SYMMETRIC KEY enctstkey DECRYPTION BY CERTIFICATE enctstcert; backup database SDBAUtility to disk ='N:\Program Files\Microsoft SQL Server \MSSQL10.S605181DL2SQL08\SDBAUtility.bak'

restored SDBAUTILITY database in S605181CH3SQL06: RESTORE DATABASE [SDBAUtility] FROM DISK = N'D:\SDBAUtility.bak' WITH FILE = 1, MOVE N'SDBAUtility' TO N'H:\Program Files\Microsoft SQL Server \MSSQL10.S605181CH3SQL06\MSSQL\DATA\SDBAUTILITY.mdf', MOVE N'SDBAUtility_log' TO N'I:\Program Files\Microsoft SQL Server \MSSQL10.S605181CH3SQL06\MSSQL\Data\SDBAUTILITY_1.ldf', NOUNLOAD, STATS = 10 GO use SDBAUtility Open MASTER KEY DECRYPTION BY PASSWORD = 'enctTERstxi*^*&%'; alter MASTER KEY add ENCRYPTION BY SERVICE MASTER KEY OPEN SYMMETRIC KEY enctstkey DECRYPTION BY CERTIFICATE enctstcert;

Comments

Page 155 of 211

Issue 167: steps to implement Symmetric key encryption - part 2 Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 24-Jun-11 Encryption-SQL Server

G(0)

Description some time open Master key by password and OPEN Symmetric key by certificate gives you an error.. So, take
OPEN MASTER KEY DECRYPTION BY PASSWORD = 'hj123DF542WE123890H&^* $%(ASseutyf23igioubh123'; OPEN SYMMETRIC KEY PasswordFieldSymmetricKey DECRYPTION BY CERTIFICATE PasswordFieldCertificate; these 2 command will give error if you restore the database to other server and try to decrypt the column. So in source server run the command This is a script which I ran on source server. BACKUP MASTER KEY TO FILE = 'P:\Backup\masterkey.bak' ENCRYPTION BY PASSWORD = 'hj123DF542WE123890H&^*$%(ASseutyf23igioubh123' and in destination server run the command like : Restore master key from file ='M:\masterkey.bak' DECRYPTION BY PASSWORD ='hj123DF542WE123890H&^*$%(ASseutyf23igioubh123' ENCRYPTION BY PASSWORD ='hj123DF542WE123890H&^*$%(ASseutyf23igioubh12345' force --- new password will generate

Comments Issue 168: How to get SqlText from any SPID. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 27-Jun-11 Blocking query

G(0)

Description DECLARE @Handle binary(20) SELECT @Handle = sql_handle FROM sysprocesses WHERE spid = 61 SELECT * FROM ::fn_get_sql(@Handle) Comments

Page 156 of 211

Issue 169: CSOSQ01__SQL_2005_Perf_Stats_Snapshot_Startup.OUT file Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 30-Jun-11 CSOSQ01__SQL_2005_Perf_Stats_S

G(0)

Description

In the CSOSQ01__SQL_2005_Perf_Stats_Snapshot_Startup.OUT file, combined with the top 50 query plan statistics, we can find the query plans that lead to more I/O consumed. Please see the Missing Indexes section in the CSOSQ01__SQL_2005 _Perf_Stats_Snapshot_Startup.OUT file, which shows an indicator of the (estimated) improvement ( in the "improvement_measure" column) that might be seen if the specified indexes (in the create_index_statement column) was created.

Comments

Page 157 of 211

Issue 170: Suspended" Job - syspolicy_purge_history when trying to run multiple times Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 08-Nov-11

G(0)

Description
Hi, The error indicates the invalid location of SQLPS.exe file. To troubleshoot the issue, please follow the below steps: 1. Execute the following statements to check the location of SQLPS.exe file. SELECT * FROM msdb.dbo.syssubsystems WHERE start_entry_point ='PowerShellStart' 2. Verify the SQLPS.exe file is located in the path as per step 1. 3. If you cannot find the SQLPS.exe in the path above, search for SQLPS.exe on the server and correct the path recorded in the msdb.dbo.syssubsystems table by using the following statements: Use msdb; GO sp_configure 'allow updates', 1 ; RECONFIGURE WITH OVERRIDE ; GO UPDATE msdb.dbo.syssubsystems SET agent_exe='<full_path>' WHERE start_entry_point ='PowerShellStart'; GO sp_configure 'allow updates', 0; RECONFIGURE WITH OVERRIDE ; GO 4. Confirm that SQLPS.exe file path has changed by running the below script once again: SELECT * FROM msdb.dbo.syssubsystems WHERE start_entry_point ='PowerShellStart' 5. Restart SQL Server Agent Service.

If there are any more questions, please let me know. Thanks.

Comments [Version: 11/8/2011 2:53:55 AM ] http://social.msdn.microsoft.com/Forums/en/sqldatabaseengine/thread/8d4f0776-7086-4f82-bceb52286e4a9842

Page 158 of 211

Issue 171: To get the last update statistics & then update the statistics of Table.. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 08-Nov-11 statistics update

G(0)

Description

To get the last update stats


select a.id as 'ObjectID',isnull(a.name,'Heap') as 'IndexName' ,b.name as tablename, stats_date(id,indid) as stats_last_updated_time, a.rowmodctr as 'Row count modified after last stats update' from sys.sysindexes as a inner join sys.objects as b on a.id=b.object_id where b.type='U' How to Update Statistics of a database table.. ===================================== Update all statistics on a table UPDATE STATISTICS Sales.SalesOrderDetail -- Update a specific index on a table UPDATE STATISTICS Sales.SalesOrderDetail IX_SalesOrderDetail -- Update one column on a table specifying sample size UPDATE STATISTICS Production.Product(Products) WITH SAMPLE 50 PERCENT

Comments Issue 172: Start SQLBrowser service with c option in command prompt. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 08-Nov-11 Browser Service

G(0)

Description
C:\Program Files (x86)\Microsoft SQL Server\90\Shared>sqlbrowser.exe -c

Comments

Page 159 of 211

Issue 173: PortQuery Application related and browser service is not coming up. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 08-Nov-11 PortQuery

G(0)

Description

Downloaded portqry application and executed below command . d:\PortQryV2>PortQry.exe -n local -e 1434 -p UDP if 1434 port is showing filtered then restart sql server browser service.
Comments

Page 160 of 211

Issue 174: Configuring Windows 2008 Storage Server for iSCSI Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 08-Nov-11 ISCSI

G(0)

Description

Configuring Windows 2008 Storage Server for iSCSI First, obtain Windows 2008 Storage Server from the MSDN site and also download Windows Server iSCSI CD. Steps for configuring iSCSI target on storage server: 1. Install Windows 2008 Storage Server x64 (name it SAN or whatever you like) 2. Install latest patches and service packs 3. Create domain on it (not recommended, only for demo purposes) 4. Install iSCSI x64 target 5. From Administrative tools start Microsoft iSCSI Software Target 6. Right click on iSCSI Target and Create new one 1. Type in name (eg. Storage) 2. On iSCSI initiators Identifiers page click advanced and add IP addresses of your two nodes that will be accessing this target 7. Repeat step 5 and create another target and name it Quorum 8. Now we have to create disk for iSCSI target 9. Right click on Storage iSCSI target and select third option from the top 1. On File option enter location of vhd file (eg. C:\storage.vhd) 2. Enter size of the disk (min. 30 GB) 10. Repeat step 8 for Quorum iSCSI target (eg. C:\quorum.vhd, min 512 MB ) Now we have created two disk resources on our storage server. Adding disk resources to NODE1 and NODE2 1. Install Windows Server 2008 R2 Enterprise on two remaining computers (I named them NODE1 and NODE2 for easier management) 2. Install latest patches and service packs 3. Connect two nodes via private network 4. Add both nodes to domain created on SAN storage server 5. Install Hyper-V role and Failover Cluster feature on both nodes 6. Shutdown NODE2 (IMPORTANT) 7. On NODE1 start iSCSI initiator from Administrative tools 1. Select Yes to start automatically if asked 2. Select OK to open required ports (for demo purposes you can disable firewall on all three computers, but for production open required ports manually) 3. Select Discovery 4. Click Discover Portal 5. Enter IP Address of SAN server and click OK 6. Select Targets (you should see two targets) 7. Select each target and click Connect 8. Select Volumes and Devices 9. Click Auto Configure 10. Click OK 8. Open Disk Management tool from Server manager Console 9. Scroll down until you see two new disks 10. Bring them Online, Initialize them and format them with NTFS
Page 161 of 211

11. Smaller disk (Quorum) select Q as drive letter 12. Larger disk (Storage) select J as drive letter 13. Shutdown NODE1 14. Startup NODE2 15. Repeat steps 7 12 on NODE2 (you will not need to format disks again, drive letters must be same as on NODE1) 16. Startup NODE1 Now we have two nodes that are connected to the same iSCSI targets on SAN server. Creating Failover Cluster 1. On NODE1 start Failover Cluster Manger console 2. In the middle pane, click Validate a Configuration 1. Add all nodes that will be part of a cluster 2. Run all tests 3. All result should be green (ignore errors about updates) 3. Select option Create Cluster 4. Add all nodes and enter cluster name 5. When cluster is created in the tree pane right click on Storage and add both disks to it (cluster will automatically configure smaller disk, Quorum, as witness and larger disk, Storage, as storage disk) 6. Select your cluster name in the left pane 7. In the middle pane select Cluster Core Resources and verify that they are all online 1. Usually you will have to change Cluster IP address from automatic to manual, after that, bring all failed resources online Our Failover Cluster is now complete. Creating highly available virtual machine Now you can minimize Failover Cluster Manager Console on NODE1 and open Server Manager or Hyper-V console. Before you start, on NODE1 and NODE2, create new Virtual Network (External) that is connected to one of your physical network adapters (not Cluster Private Adapters). 1. Copy Windows Server 2008 ISO file to J disk on NODE1 (J disk is our iSCSI disk) 2. Open Hyper-V console, right click on NODE1 and create new virtual machine 3. Name it (eg. FailoverDemo) 4. Store it on J disk (IMPORTANT) 5. Give it 1024 MB of RAM 6. Connect it to previously created network 7. Create new virtual disk, size 20 GB on J disk (IMPORTANT) 8. On installation options select second bullet and select ISO image that you copied on J disk 9. Click Finish 10. Right click on newly created Virtual machine and select Settings 11. On the lover left side select Automatic Start action and select Nothing 12. Click OK Now you can minimize Hyper-V console and maximize Failover Cluster Manager Console. 1. Right click Services and applications and select Configure a Service or Application 2. Find Virtual Machine near the bottom, select it and click next 3. Select newly created virtual machine and click Next Our virtual machine is now configured as highly available. Restore Hyper-V console and start your virtual machine. It should boot from ISO DVD image that is attached to it and install Windows Server 2008 R2 operating system. After installation is completed, install latest Hyper-V additions into the virtual machine.
Comments

Page 162 of 211

Issue 175: Obtain the list of checkpointed keys by using the following command: cluster res /checkpoints Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 08-Nov-11 Cluster

G(0)

Description
cluster res /checkpoints

Comments

Page 163 of 211

Issue 176: commands to disable the cluster checkpoint for the specific registry commands to disable the cluster checkpoint for the specific registry Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 08-Nov-11 Cluster

G(0)

Description
commands to disable the cluster checkpoint for the specific registry subkey: For an instance of SQL Server 2008 R2, run the following command: cluster . resource "SQL Network Name (<InstanceName>)" /removecheckpoints:"Software\Microsoft\Microsoft SQL Server\MSSQL10_50.x\MSSQLSERVER" For an instance of SQL Server 2008, run the following command: cluster . resource "SQL Network Name (<InstanceName>)" /removecheckpoints:"Software\Microsoft\Microsoft SQL Server\MSSQL10.x\MSSQLSERVER" For an instance of SQL Server 2005, run the following command: cluster res "SQL Server (<InstanceName>)" /removecheck: "Software\Microsoft\Microsoft SQL Server\MSSQL.x \MSSQLSERVER" For the default instance of SQL Server 2000, run the following commands: cluster res "SQL Server" /removecheck: "Software\Microsoft\MSSQLServer\MSSQLSERVER" cluster res "SQL Server" /removecheck: "Software\Microsoft\MSSQLServer\Cluster" Note Example:

C:\Documents and Settings\Administrator.STL>cluster res "SQL Server (S605181CH3SQL13)" /removecheck: "Software\Microsoft\Microsoft SQL Server\MSSQL.1\MSSQLSERVER" Removing registry checkpoint 'Software\Microsoft\Microsoft SQL Server\MSSQL.1 \MSSQLSERVER' for resource 'SQL Server (S605181CH3SQL13)'... C:\Documents and Settings\Administrator.STL> Revert the changes Addcheck:

In 2008 C:\Users\rakesh.kumar>cluster . resource "SQL Server" /removecheckpoints:"software \Microsoft\Microsoft SQL Server\MSSQL10_50.MSSQLServer\MSSQLServer" :sqlSQL Serv Removing registry checkpoint 'software\Microsoft\Microsoft SQL Server\MSSQL10_ 50.MSSQLServer\MSSQLServer' for resource 'SQL Server'... System error 2 has occurred (0x00000002).
Page 164 of 211

The system cannot find the file specified.


Comments Issue 177: converting blg to csv file Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 20-Nov-11 Perfmon Counter

G(0)

Description
relog filename.blg -f CSV -o newfile.csv

Comments

Issue 178: How much memory is each SQL Server database using Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 19-Feb-12 Memory

G(0)

Description
SELECT (CASE WHEN ([is_modified] = 1) THEN 'Dirty' ELSE 'Clean' END) AS 'Page State', (CASE WHEN ([database_id] = 32767) THEN 'Resource Database' ELSE DB_NAME (database_id) END) AS 'Database Name', COUNT (*) AS 'Page Count' FROM sys.dm_os_buffer_descriptors GROUP BY [database_id], [is_modified] ORDER BY [database_id], [is_modified]; GO

Comments

Page 165 of 211

Issue 179: T-SQL to identify the Top 20 most costly queries in terms of Total CPU Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 19-Feb-12 Memory

G(0)

Description
SELECT TOP 20 qs.sql_handle, qs.execution_count, qs.total_worker_time AS Total_CPU, total_CPU_inSeconds = --Converted from microseconds qs.total_worker_time/1000000, average_CPU_inSeconds = --Converted from microseconds (qs.total_worker_time/1000000) / qs.execution_count, qs.total_elapsed_time, total_elapsed_time_inSeconds = --Converted from microseconds qs.total_elapsed_time/1000000, st.text, qp.query_plan FROM sys.dm_exec_query_stats AS qs CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st CROSS apply sys.dm_exec_query_plan (qs.plan_handle) AS qp ORDER BY qs.total_worker_time DESC

Comments Issue 180: Find Top N costly query plans in adhoc batches or modules Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 19-Feb-12

G(0)

Description
~~http://blogs.msdn.com/b/sqltips/archive/2005/10/05/top-n-costly-query-plans.aspx

Comments

Page 166 of 211

Issue 181: Generating Deadlock Graph Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 01-Jun-12 DeadLock

G(0)

Description
select CAST( REPLACE( REPLACE(XEventData.XEvent.value('(data/value)[1]', 'varchar(max)'), '<victim-list>', '<deadlock><victim-list>'), '<process-list>','</victim-list><process-list>') as xml) as DeadlockGraph FROM (select CAST(target_data as xml) as TargetData from sys.dm_xe_session_targets st join sys.dm_xe_sessions s on s.address = st.event_session_address where name = 'system_health') AS Data CROSS APPLY TargetData.nodes ('//RingBufferTarget/event') AS XEventData (XEvent) where XEventData.XEvent.value('@name', 'varchar(4000)') = 'xml_deadlock_report'

Comments Issue 182: Query to generate sql text from sql handle Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 01-Jun-12

G(0)

Description Comments

Page 167 of 211

Issue 183: Missing index with advantage. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 23-Jul-12 Indexing

G(0)

Description
SELECT user_seeks * avg_total_user_cost * (avg_user_impact * 0.01) AS [index_advantage], migs.last_user_seek, mid.[statement] AS [Database.Schema.Table], mid.equality_columns, mid.inequality_columns, mid.included_columns,migs.unique_compiles, migs.user_seeks, migs.avg_total_user_cost, migs.avg_user_impact FROM sys.dm_db_missing_index_group_stats AS migs WITH (NOLOCK) INNER JOIN sys.dm_db_missing_index_groups AS mig WITH (NOLOCK) ON migs.group_handle = mig.index_group_handle INNER JOIN sys.dm_db_missing_index_details AS mid WITH (NOLOCK) ON mig.index_handle = mid.index_handle WHERE mid.database_id = DB_ID() AND user_seeks * avg_total_user_cost * (avg_user_impact * 0.01) > 9000 -- Set this to Whatever

Comments

Page 168 of 211

Issue 184: I/O requests taking longer than 15 seconds to complete on file Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 08-Sep-12 DeadLock

G(0)

Description
I/O requests taking longer than 15 seconds to complete on file RATE THIS Karthick P.K - karthick krishnamurthy 26 Jun 2012 8:23 AM 2 SQL Server I/O Bottlenecks ( I/O requests taking longer than 15 seconds to complete on file )

Following are common reasons for I/O Bottleneck in SQL Server. 1. SQL Server is spawning more I/O requests than what I/O disk subsystem could handle. 2 . There could be an Issue with I/O subsystem (or) driver/firmware issue (or) Misconfiguration in I/O Subsystem so the Disks are performing very slow and hence SQL Server is affected. 3. Some other process on the system is saturating the disks with I/O requests. Common application includes AV Scan,System Backup Etc. So I/O requests posted by SQL Server becomes slow.

I/O Bottleneck SQL Server performance highly relies on the Disk performance. SQL Server I/O Bottleneck can be identified through

1. PAGEIOLATCH_xx or WRITELOG wait types in Sysprocesses and other DMV's 2. I/O taking longer than 15 seconds in SQL Server Errorlog. { SQL Server has encountered X occurrence(s) of I/O requests taking longer than 15 seconds to complete on file [L:\mssql\data\File.ldf] in database [IOTEST (7). The OS file handle is 0x000006A4. The offset of the latest long I/O is: 0x000001e616fa00 } 3. By looking at I/O latch wait statistics in sys.dm_os_wait_stats { Select wait_type, waiting_tasks_count,

Page 169 of 211

wait_time_ms from sys.dm_os_wait_stats where wait_type like 'PAGEIOLATCH%' order by wait_type }

4. By looking at pending I/O requests and isolating the disks,File and database in which we have I/O Bottleneck. { select database_id, file_id, io_stall, io_pending_ms_ticks, scheduler_address from sys.dm_io_virtual_file_stats(NULL, NULL)t1, sys.dm_io_pending_io_requests as t2 where t1.file_handle = t2.io_handle }

How to troubleshoot? Disk Perfmon counters can be used to identify which of above three is causing I/O Bottleneck. Disk Bytes /sec -- > Total read and write to disk per second in bytes Process:IO Data Bytes/Sec --> Total read and write to disk per second in bytes by each process. Buffer Manager: Page Read/sec + Page Writes/sec -->Total read and write to disk per second in bytes by SQL Server process. Disk sec/Transfer --> Time taken to perform the I/O operation Ideal value for Disk sec/Transfer is 0.005-0.015 sec. If you consistently notice this counter is beyond 0.015 then there is a serious I/O bottleneck. Look for Disk Bytes /sec immediately If it is below 150 MB for SAN disk and Below 50 MB for Single disk then the problem is with I/O subsystem Engage hardware vendor.

If (Disk sec/Transfer > ==0.015 Consistently) and ( (Disk Bytes /sec < 150 (For San)) or (Disk Bytes /sec < 50 (For Local) or (Disk Bytes /sec < Speed of disk as per Vendor )) { There is Issue with I/O subsystem (or) driver/firmware issue (or) Misconfiguration in I/O Subsystem. } If (Disk sec/Transfer > ==0.015 Consistently) and ( (Disk Bytes /sec >= 150 (For San)) or (Disk Bytes /sec >= 50 (For Local) or (Disk Bytes /sec >= Speed of disk as per Vendor ))

Page 170 of 211

{ Identify the process which is posting excessive I/O request using Process:IO Data Bytes/Sec. If ( Identified process == SQLServer.exe ) { Identify and tune the queries which is Spawning excessive I/O. (Reads+Writes column in profiler, Dashboard reports or sys.dm_exec_query_stats and sys.dm_exec_sql_text can be used to identify the query). Use DTA to tune the query } If ( Identified process != SQLServer.exe ) { Engage the owner of application which is spawning excessive I/O } }

Comments

Page 171 of 211

Issue 185: Gathering information about the open transaction. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 12-Sep-12

G(0)

Description
SELECT s t . s es s i on_i d , s t . i s _us er _t r ans ac t i on , dt . dat abas e_t r ans ac t i on_begi n_t i m e , dt . dat abas e_t r ans ac t i on_l og_r ec or d_c ount , dt . dat abas e_t r ans ac t i on_l og_by t es _us ed FROM s y s . dm _t r an_s es s i on_t r ans ac t i ons s t J OI N s y s . dm _t r an_dat abas e_t r ans ac t i ons dt ON s t . t r ans ac t i on_i d = dt . t r ans ac t i on_i d AND dt . dat abas e_i d = DB_I D( ' m as t er ' ) W HERE s t . s es s i on_i d = <SPI D> /*

_t r an_sessi on_t r ansact i ons and In SQL Server 2005 and 2008, the sys. dm sys. dm _t r an_dat abase_t r ansact i ons DMVs can be used to gather information specific to the open transaction including the transaction start time, number of log records used by the open transaction, as well as the bytes of log space used, as shown in Listing 8.6. /*
Comments

Page 172 of 211

Issue 186: The transaction log for database 'PCT_DEV' is full due to 'LOG_BACKUP Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 06-Oct-12

G(0)

Description
Alter failed for Database 'PCT_DEV'. (Microsoft.SqlServer.Smo) The transaction log for database 'PCT_DEV' is full due to 'LOG_BACKUP'. (Microsoft SQL Server, Error: 9002)

Comments [Version: 10/6/2012 11:13:31 AM ] An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo) -----------------------------The transaction log for database 'PCT_DEV' is full due to 'LOG_BACKUP'. (Microsoft SQL Server, Error: 9002) For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&ProdVer=11.00.2100&EvtSrc=MSSQ LServer&EvtID=9002&LinkId=20476 -----------------------------BUTTONS: OK ------------------------[Version: 10/6/2012 11:13:58 AM ] An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo) -----------------------------The transaction log for database 'PCT_DEV' is full due to 'LOG_BACKUP'. (Microsoft SQL Server, Error: 9002) For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&ProdVer=11.00.2100&EvtSrc=MSSQ LServer&EvtID=9002&LinkId=20476 -----------------------------BUTTONS: OK -------------------------

Page 173 of 211

Issue 187: HMK Replication Tutorial Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 06-Oct-12 Replication Concept

G(1)

Description Comments

Issue 188: 'An inconsistency was detected during an internal operation in database Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 07-Oct-12 Corruption

G(0)

Description
I get following massage repeatedly in duration of 2 or 3 days. Database name is 'DBNAME'. 'An inconsistency was detected during an internal operation in database 'DBNAME'(ID:16) on page (1:524021). Please contact technical support. Reference number 4.' I run following script and it worked out each and every time. GO ALTER DATABASE DBNAME SET EMERGENCY ALTER DATABASE DBNAME SET SINGLE_USER DBCC CHECKDB (DBNAME, REPAIR_ALLOW_DATA_LOSS) WITH NO_INFOMSGS; DBCC CHECKDB WITH NO_INFOMSGS; ALTER DATABASE DBNAME SET MULTI_USER But I want to know the issue and permanent solution for them. I have used 'SELECT * FROM msdb..suspect_pages' but it does not give relevant results for my problem.

Comments

Page 174 of 211

Issue 189: Database suspect Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 07-Oct-12 Corruption

G(0)

Description
Introduction If your project's database is in suspect mode, then no transaction will take place until and unless you repair your database. That causes a show stopper for your up and running application. Here, you will find a way to get out of this. Background Your Database is in Suspect Mode. I guess, you haven't experienced this problem till now. But, if it comes to you and if the database is LIVE, then it's time to read this article to get out of this tension. Using the Code If you find your database in Suspect mode, then please keep your nerve strong. Just proceed step by step what I am written below. I think you will get out of this trouble. SQL Server 2005 introduced a new DB Status called Emergency. This mode can change the DB from Suspect mode to Emergency mode, so that you can retrieve the data in read only mode. The steps are... After executing the script given below, you will get back your database in operational mode. Actually I have tried with two of my existing live systems and found no data loss. Note: Obviously there are two more options available. Run REPAIR_ALLOW_DATA_LOSS to ensure the database is returned to a structurally and transitionally consistent state. Here are a few things to bear in mind about emergency mode repair: it's a one-way operation. Anything it does cannot be rolled back or undone. If this worries you (if someone ever got into that state, then surely don't have the healthy concern about data that they should have in the first place) then make a copy of the damaged database before you run emergency mode repair. As it's a one-way operation, you cannot wrap it in an explicit user-transaction. It's the only repair option available in emergency mode - if you try to use REPAIR_REBUILD, then it won't work. To get the exact reason of a database going into suspect mode can be found using the following query, DBCC CHECKDB (YourDBname) WITH NO_INFOMSGS, ALL_ERRORMSGS EXEC sp_resetstatus 'yourDBname'; ALTER DATABASE yourDBname SET EMERGENCY DBCC checkdb('yourDBname') ALTER DATABASE yourDBname SET SINGLE_USER WITH ROLLBACK IMMEDIATE DBCC CheckDB ('yourDBname', REPAIR_ALLOW_DATA_LOSS) ALTER DATABASE yourDBname SET MULTI_USER

Comments

Page 175 of 211

Issue 190: HOW MUCH MEMORY IS NEEDED TAKEN FOR MY DATABASE BACKUP Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 19-Oct-12 Backup and Restore

G(1)

Description Comments

Page 176 of 211

Issue 191: Main catalog views: sys.server_principals, dbname.sys.database_principals Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 19-Oct-12 Login_User_Schema

G(0)

Description

Logins
Stored in the master database Main catalog views: sys.server_principals, dbname.sys.database_principals Make sure you have the necessary logins with the same name, and for a SQL Server login also password and SID on the destination server. This is probably the most obvious and known issue. A user in a database is "mapped" to a login. Inside the database, you can list the users through the sys.database_principals catalog view. Pay special attention to the sid column. The user is connected to a a login, sys.server_principals which also has a sid column. The sid columns is the mapping from the user to the login. For Windows logins, the SID is produced by the AD or SAM database, and unless you move the database to a SQL Server in a different domain, then all you have to do is to create the same Windows login on the new server. For a SQL Server logins, SQL Server will invent a sid when you create the login. So, if you just create the login on the new server, the sids won't match. If you use the GUI and look at the login on the new server, you won't see it mapped to the database. If you use the GUI to list the user inside the database, you won't see it mapped to a login. This is what we call an "orphaned user". So, SQL Server logins and users for those logins require a bit more attention than Windows logins. This query will list orphaned users in the database (it doesn't differentiate a deliberate user without login in source db, easiest is probably to check them manually): SELECT * FROM sys.database_principals AS d WHERE NOT EXISTS ( SELECT * FROM sys.server_principals AS s WHERE s.sid = d.sid ) AND type_desc = 'SQL_USER' AND name NOT IN('guest', 'INFORMATION_SCHEMA', 'sys') If the login already exist on the new server, then you can adjust the sid for the user inside the database so it matches the right login. (The old-fashioned way to do this is using sp_change_users_login, but as of SQL Server 2005 sp2, we are recommended to use the ALTER USER command instead.) Here's an example of using the ALTER USER command to map to an existing login: ALTER USER Joe WITH LOGIN = Joe

Page 177 of 211

If the logins do not exist in the destination instance, then I suggest you use a utility to script them on the source server and from that script create them on destination server; making sure thay have the same sid and also password. There is a "Transfer Logins" SSIS task, but that doesn't carry over the password, so instead I suggest you use the sp_help_revlogin stored procedure. Use this if the source server is 7.0 or 2000 or this if the source server is 2005 or more recent. These procedures will also take care of server roles assignment and also carry over Windows logins.

Comments Issue 192: The DEFAULT_SCHEMA clause cannot be used with a Windows group or with principals mapped to certificates or asymmetric keys. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 19-Oct-12

G(0)

Description
Msg 15259, Level 16, State 2, Line 1 The DEFAULT_SCHEMA clause cannot be used with a Windows group or with principals mapped to certificates or asymmetric keys.

Comments

Page 178 of 211

Issue 193: AlwaysOn Availability Groups PowerShell Commands Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 20-Oct-12 PowerShell-SQL Command

G(0)

Description

AlwaysOn Availability Groups PowerShell Commands


Below are the AlwaysOn Availability Groups Powershell commands. Disable-SqlHADRService Disables the SQL HADR service on a server instance. Enable-SqlHADRService Enables the SQL HADR service on an instance of Microsoft SQL Server 2012. New-SqlHadrEndPoint Creates a new database mirroring endpoint on a server instance. This endpoint is required for data movement between primary and secondary databases. Set-SqlHadrEndpoint Changes the properties of an existing database mirroring endpoint, such as the name, state, or authentication properties. Backup-SqlDatabase Creates a data or log backup Restore-SqlDatabase Restores a backup. Disable-SqlAvailabilityGroup Takes an availability group offline. Enable-SqlAvailabilityGroup Brings an availability group online. New-SqlAvailabilityGroup Creates a new availability group. Remove-SqlAvailabilityGroup Deletes availability group. Set-SqlAvailabilityGroup Sets the properties of an availability group; take an availability group online/offline Switch-SqlAvailabilityGroup Initiates one of the following forms of failover: A forced failover of an availability group (with possible data loss). A manual failover of an availability group. Add-SqlAvailabilityDatabase On the primary replica, adds a database to an availability group. On a secondary replica, joins a secondary database to an availability group. Remove-SqlAvailabilityDatabase On the primary replica, removes the database from the availability group. On a secondary replica, removes the local secondary database from the local
Page 179 of 211

secondary replica. Resume-SqlAvailabilityDatabase Resumes the data movement for a suspended availability database. Suspend-SqlAvailabilityDatabase Suspends the data movement for an availability database
Comments Issue 195: AlwaysOn-PPT by Denny Cherry. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 20-Oct-12 AlwaysOn

G(1)

Description Comments

Issue 196: Import-Module SQLPS -DisableNameChecking Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 20-Oct-12 PowerShell-SQL Command

G(0)

Description

Import the SQLPS module as shown below. This will make all of the SQLPS related cmdlets available on the current PowerShell session.
Comments [Version: 10/20/2012 7:47:20 AM ] This command will enable you to enter into SQLPS related cmdlets available to PowerShell session.

Page 180 of 211

Issue 197: PowerShell (v3) - Get a Numbered List of Cmdlets Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 20-Oct-12 PowerShell-SQL Command

G(0)

Description

$a=1; Get-Command -CommandType cmdlet | ForEach-Object {"$($a): $($_.name)"; $a++ } output: will output this: 1: Add-BitsFile 2: Add-Computer 3: Add-Content 4: Add-History 5: Add-JobTrigger 6: Add-Member 7: Add-PSSnapin 8: Add-RoleMember 9: Add-SqlAvailabilityDatabase 10: Add-SqlAvailabilityGroupListenerStaticIp 11: Add-Type 12: Backup-ASDatabase 13: Backup-SqlDatabase 14: Checkpoint-Computer 15: Clear-Content 16: Clear-EventLog 17: Clear-History 18: Clear-Item 19: Clear-ItemProperty 20: Clear-Variable 21: Compare-Object 22: Complete-BitsTransfer 23: Complete-Transaction 24: Connect-PSSession 25: Connect-WSMan 26: ConvertFrom-Csv 27: ConvertFrom-Json 28: ConvertFrom-SecureString 29: ConvertFrom-StringData 30: Convert-Path 31: ConvertTo-Csv 32: ConvertTo-Html 33: ConvertTo-Json 34: ConvertTo-SecureString 35: ConvertTo-Xml
Page 181 of 211

36: Convert-UrnToPath 37: Copy-Item 38: Copy-ItemProperty 39: Debug-Process 40: Decode-SqlName 41: Disable-ComputerRestore 42: Disable-JobTrigger 43: Disable-PSBreakpoint 44: Disable-PSRemoting 45: Disable-PSSessionConfiguration 46: Disable-ScheduledJob 47: Disable-SqlAlwaysOn 48: Disable-WSManCredSSP 49: Disconnect-PSSession 50: Disconnect-WSMan 51: Enable-ComputerRestore 52: Enable-JobTrigger 53: Enable-PSBreakpoint 54: Enable-PSRemoting 55: Enable-PSSessionConfiguration 56: Enable-ScheduledJob 57: Enable-SqlAlwaysOn 58: Enable-WSManCredSSP 59: Encode-SqlName 60: Enter-PSSession 61: Exit-PSSession 62: Export-Alias 63: Export-Clixml 64: Export-Console 65: Export-Counter 66: Export-Csv 67: Export-FormatData 68: Export-ModuleMember 69: Export-PSSession 70: ForEach-Object 71: Format-Custom 72: Format-List 73: Format-Table 74: Format-Wide 75: Get-Acl 76: Get-Alias 77: Get-AppLockerFileInformation 78: Get-AppLockerPolicy 79: Get-AuthenticodeSignature 80: Get-BitsTransfer 81: Get-ChildItem 82: Get-CimAssociatedInstance 83: Get-CimClass 84: Get-CimInstance 85: Get-CimSession 86: Get-Command 87: Get-ComputerRestorePoint
Page 182 of 211

88: Get-Content 89: Get-ControlPanelItem 90: Get-Counter 91: Get-Credential 92: Get-Culture 93: Get-Date 94: Get-Event 95: Get-EventLog 96: Get-EventSubscriber 97: Get-ExecutionPolicy 98: Get-FormatData 99: Get-Help 100: Get-History 101: Get-Host 102: Get-HotFix 103: Get-Item 104: Get-ItemProperty 105: Get-Job 106: Get-JobTrigger 107: Get-Location 108: Get-Member 109: Get-Module 110: Get-PfxCertificate 111: Get-Process 112: Get-PSBreakpoint 113: Get-PSCallStack 114: Get-PSDrive 115: Get-PSProvider 116: Get-PSSession 117: Get-PSSessionConfiguration 118: Get-PSSnapin 119: Get-Random 120: Get-ScheduledJob 121: Get-ScheduledJobOption 122: Get-Service 123: Get-TraceSource 124: Get-Transaction 125: Get-TroubleshootingPack 126: Get-TypeData 127: Get-UICulture 128: Get-Unique 129: Get-Variable 130: Get-WinEvent 131: Get-WmiObject 132: Get-WSManCredSSP 133: Get-WSManInstance 134: Group-Object 135: Import-Alias 136: Import-Clixml 137: Import-Counter 138: Import-Csv 139: Import-LocalizedData
Page 183 of 211

140: Import-Module 141: Import-PSSession 142: Invoke-ASCmd 143: Invoke-CimMethod 144: Invoke-Command 145: Invoke-Expression 146: Invoke-History 147: Invoke-Item 148: Invoke-PolicyEvaluation 149: Invoke-ProcessCube 150: Invoke-ProcessDimension 151: Invoke-ProcessPartition 152: Invoke-RestMethod 153: Invoke-Sqlcmd 154: Invoke-TroubleshootingPack 155: Invoke-WebRequest 156: Invoke-WmiMethod 157: Invoke-WSManAction 158: Join-Path 159: Join-SqlAvailabilityGroup 160: Limit-EventLog 161: Measure-Command 162: Measure-Object 163: Merge-Partition 164: Move-Item 165: Move-ItemProperty 166: New-Alias 167: New-AppLockerPolicy 168: New-CimInstance 169: New-CimSession 170: New-CimSessionOption 171: New-Event 172: New-EventLog 173: New-Item 174: New-ItemProperty 175: New-JobTrigger 176: New-Module 177: New-ModuleManifest 178: New-Object 179: New-PSDrive 180: New-PSSession 181: New-PSSessionConfigurationFile 182: New-PSSessionOption 183: New-PSTransportOption 184: New-PSWorkflowExecutionOption 185: New-RestoreFolder 186: New-RestoreLocation 187: New-ScheduledJobOption 188: New-Service 189: New-SqlAvailabilityGroup 190: New-SqlAvailabilityGroupListener 191: New-SqlAvailabilityReplica
Page 184 of 211

192: New-SqlHADREndpoint 193: New-TimeSpan 194: New-Variable 195: New-WebServiceProxy 196: New-WinEvent 197: New-WSManInstance 198: New-WSManSessionOption 199: Out-Default 200: Out-File 201: Out-GridView 202: Out-Host 203: Out-Null 204: Out-Printer 205: Out-String 206: Pop-Location 207: Push-Location 208: Read-Host 209: Receive-Job 210: Receive-PSSession 211: Register-CimIndicationEvent 212: Register-EngineEvent 213: Register-ObjectEvent 214: Register-PSSessionConfiguration 215: Register-ScheduledJob 216: Register-WmiEvent 217: Remove-BitsTransfer 218: Remove-CimInstance 219: Remove-CimSession 220: Remove-Computer 221: Remove-Event 222: Remove-EventLog 223: Remove-Item 224: Remove-ItemProperty 225: Remove-Job 226: Remove-JobTrigger 227: Remove-Module 228: Remove-PSBreakpoint 229: Remove-PSDrive 230: Remove-PSSession 231: Remove-PSSnapin 232: Remove-RoleMember 233: Remove-SqlAvailabilityDatabase 234: Remove-SqlAvailabilityGroup 235: Remove-SqlAvailabilityReplica 236: Remove-TypeData 237: Remove-Variable 238: Remove-WmiObject 239: Remove-WSManInstance 240: Rename-Computer 241: Rename-Item 242: Rename-ItemProperty 243: Reset-ComputerMachinePassword
Page 185 of 211

244: Resolve-Path 245: Restart-Computer 246: Restart-Service 247: Restore-ASDatabase 248: Restore-Computer 249: Restore-SqlDatabase 250: Resume-BitsTransfer 251: Resume-Job 252: Resume-Service 253: Resume-SqlAvailabilityDatabase 254: Save-Help 255: Select-Object 256: Select-String 257: Select-Xml 258: Send-MailMessage 259: Set-Acl 260: Set-Alias 261: Set-AppLockerPolicy 262: Set-AuthenticodeSignature 263: Set-BitsTransfer 264: Set-CimInstance 265: Set-Content 266: Set-Date 267: Set-ExecutionPolicy 268: Set-Item 269: Set-ItemProperty 270: Set-JobTrigger 271: Set-Location 272: Set-PSBreakpoint 273: Set-PSDebug 274: Set-PSSessionConfiguration 275: Set-ScheduledJob 276: Set-ScheduledJobOption 277: Set-Service 278: Set-SqlAvailabilityGroup 279: Set-SqlAvailabilityGroupListener 280: Set-SqlAvailabilityReplica 281: Set-SqlHADREndpoint 282: Set-StrictMode 283: Set-TraceSource 284: Set-Variable 285: Set-WmiInstance 286: Set-WSManInstance 287: Set-WSManQuickConfig 288: Show-Command 289: Show-ControlPanelItem 290: Show-EventLog 291: Sort-Object 292: Split-Path 293: Start-BitsTransfer 294: Start-Job 295: Start-Process
Page 186 of 211

296: Start-Service 297: Start-Sleep 298: Start-Transaction 299: Start-Transcript 300: Stop-Computer 301: Stop-Job 302: Stop-Process 303: Stop-Service 304: Stop-Transcript 305: Suspend-BitsTransfer 306: Suspend-Job 307: Suspend-Service 308: Suspend-SqlAvailabilityDatabase 309: Switch-SqlAvailabilityGroup 310: Tee-Object 311: Test-AppLockerPolicy 312: Test-ComputerSecureChannel 313: Test-Connection 314: Test-ModuleManifest 315: Test-Path 316: Test-PSSessionConfigurationFile 317: Test-SqlAvailabilityGroup 318: Test-SqlAvailabilityReplica 319: Test-SqlDatabaseReplicaState 320: Test-WSMan 321: Trace-Command 322: Unblock-File 323: Undo-Transaction 324: Unregister-Event 325: Unregister-PSSessionConfiguration 326: Unregister-ScheduledJob 327: Update-FormatData 328: Update-Help 329: Update-List 330: Update-TypeData 331: Use-Transaction 332: Wait-Event 333: Wait-Job 334: Wait-Process 335: Where-Object 336: Write-Debug 337: Write-Error 338: Write-EventLog 339: Write-Host 340: Write-Output 341: Write-Progress 342: Write-Verbose 343: Write-Warning

Comments

Page 187 of 211

Issue 198: sqlps from databasejournal Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 20-Oct-12

G(0)

Description
http://www.databasejournal.com/features/mssql/microsoft-sql-server-2012-sqlps.html

Comments

Issue 199: All permission associated with the database with Role and User. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 23-Oct-12 Login_User_Schema

G(0)

Description

select user_name(M.role_principal_id) Role,user_name(M.member_principal_id) UserName,suser_sname(P.sid) LoginName, LOGINPROPERTY(suser_sname(P.sid),'IsLocked') IsLocked,S.is_disabled from sys.database_role_members M join sys.database_principals P on P.name=user_name(M.member_principal_id) join sys.server_principals S on S.name=suser_sname(P.sid) order by user_name(M.member_principal_id)

Comments [Version: 8/6/2013 8:07:54 AM ] http://consultingblogs.emc.com/jamiethomson/archive/2007/02/09/SQLServer-2005_3A00_-View-all-permissions--_2800_2_2900_.aspx

Page 188 of 211

Issue 200: Logins and Users permission using SUHAS Sys.database_role_members & database_principals Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 23-Oct-12 Login_User_Schema

G(0)

Description use <UserDatabaseName> go DECLARE @StrUserName varchar(200) select @StrUserName = name from master.sys.server_principals like '%<loginNameProvided>%' print @StruserName
SELECT MPI.name [User Name], RPI.name [Role Name] FROM sys.database_role_members RM JOIN sys.database_principals RPI ON RM.role_principal_id = RPI.principal_id JOIN sys.database_principals MPI ON RM.member_principal_id = MPI.principal_id WHERE MPI.name = ''+ @StruserName +'' SELECT DPri.[name] [User Name], DPer.class_desc [Object Class], object_name(major_id) [Object Name], DPer.permission_name [Permission Type], DPer.[state_desc] [Permission State] FROM sys.database_permissions DPer JOIN sys.database_principals DPri ON DPer.grantee_principal_id = DPri.principal_id WHERE DPri.[name] ='' + @StruserName +'' ORDER BY Dpri.[name]

where name

Comments

Page 189 of 211

Issue 201: create statements to recreate users, roles and permissions after a database refresh. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 24-Oct-12 Backup and Restore

G(0)

Description --This script will create statements to recreate users, roles and permissions after a database refresh. -- Specify the database name below in the 'SET @DatabaseName =' statement
DECLARE @DatabaseName varchar(255) ,@DbRole varchar(50) ,@MemberName varchar(300) ,@LoginName varchar(300) ,@Cmd varchar(2000) ,@KillId int ,@Service varchar(100) ,@Key varchar(100) ,@Value varchar(100) ,@RC int -- Set the Database Name here SET @DatabaseName = 'pi_repository' /******************************************************************** DO NOT CHANGE ANYTHING BELOW THIS LINE!!!! DO NOT CHANGE ANYTHING BELOW THIS LINE!!!! DO NOT CHANGE ANYTHING BELOW THIS LINE!!!! ********************************************************************/ SET NOCOUNT ON SET QUOTED_IDENTIFIER OFF -- VALIDATE PARAMETER: @DatabaseName IF NOT EXISTS (SELECT name FROM master..sysdatabases WHERE name = @DatabaseName) BEGIN RAISERROR('Error - Invalid parameter: @DatabaseName. This script cannot refresh a non-existant database.',16,1) GOTO ERROR END -- SCRIPT OUT ALL LOGINS PERMISSIONS IF OBJECT_ID('tempdb..#DatabaseLogins') IS NOT NULL DROP TABLE #DatabaseLogins IF OBJECT_ID('tempdb..#Commands') IS NOT NULL DROP TABLE #Commands CREATE TABLE #DatabaseLogins( DbRole varchar(50) ,MemberName varchar(300) ,MemberSID varbinary(85)) CREATE TABLE #Commands( RowId int identity(1,1) ,Cmd varchar(2000))
Page 190 of 211

ALTER TABLE #Commands ADD CONSTRAINT PK_RowId PRIMARY KEY CLUSTERED(RowId) ON [PRIMARY] SELECT @Cmd='exec '+QUOTENAME(@DatabaseName)+'.dbo.sp_helprolemember' INSERT #DatabaseLogins EXEC (@Cmd) SET @Cmd='DECLARE C CURSOR for SELECT DISTINCT t.MemberName,l.name FROM #DatabaseLogins t JOIN '+QUOTENAME(@DatabaseName)+'.dbo.sysusers u on t.MemberName = u.name JOIN master.dbo.syslogins l on u.sid = l.sid WHERE t.MemberName <> ''dbo''' EXEC (@Cmd) OPEN C FETCH NEXT FROM C INTO @MemberName,@LoginName WHILE @@FETCH_STATUS = 0 BEGIN INSERT #Commands(Cmd) SELECT 'USE '+QUOTENAME(@DatabaseName)+';if not exists (SELECT * FROM dbo.sysusers WHERE name = N'+QUOTENAME(@MemberName,char(39))+') EXEC sp_grantdbaccess N'+QUOTENAME(@LoginName,char(39))+',N'+QUOTENAME(@MemberName,char(39))+';' FETCH NEXT FROM C INTO @MemberName,@LoginName END CLOSE C DEALLOCATE C SET @Cmd='DECLARE C CURSOR for SELECT DISTINCT DbRole FROM #DatabaseLogins t JOIN '+QUOTENAME(@DatabaseName)+'.dbo.sysusers u on t.DbRole = u.name WHERE u.issqlrole = 1 and u.gid <> 0' EXEC (@Cmd) OPEN C FETCH NEXT FROM C INTO @DbRole WHILE @@FETCH_STATUS = 0 BEGIN INSERT #Commands(Cmd) SELECT DISTINCT 'USE '+QUOTENAME(@DatabaseName)+';if not exists (SELECT * FROM dbo.sysusers WHERE name = N'+QUOTENAME(@DbRole,char(39))+') EXEC sp_addrole N'+QUOTENAME(@DbRole,char(39))+';' FETCH NEXT FROM C INTO @DbRole END CLOSE C DEALLOCATE C DECLARE C CURSOR FOR SELECT DbRole,MemberName FROM #DatabaseLogins WHERE MemberName <> 'dbo' OPEN C FETCH NEXT FROM C INTO @DbRole, @MemberName WHILE @@FETCH_STATUS = 0 BEGIN INSERT #Commands(Cmd) SELECT 'USE '+QUOTENAME(@DatabaseName)+';exec sp_addrolemember N'+QUOTENAME(@DbRole,char(39))+',N'+QUOTENAME(@MemberName,char(39))+';' FETCH NEXT FROM C INTO @DbRole, @MemberName END CLOSE C DEALLOCATE C -- Create a temp table with DB Users for this database CREATE TABLE #TempUsers
Page 191 of 211

(name varchar(75)) DECLARE @SQLStr varchar(3000) SET @SQLStr = ' insert #TempUsers(name) select name from ' + @DatabaseName + '.dbo.' + 'sysusers' exec(@SQLStr) INSERT #Commands(Cmd) SELECT 'use '+QUOTENAME(@DatabaseName)+';ALTER USER ' + QUOTENAME(name) + ' WITH LOGIN = ' + QUOTENAME(name) +';' FROM master..syslogins WHERE name not in ('sa','saSIG','CIBNA\!msdba','CIBNA\dbadmin','BUILTIN \Administrators', 'CIBNA\!mssql-cm-prod','AD-ENT\SIG SQL ADMINS','AD-ENT\SIGSQLCompliance') and name not like '##%' and name not like 'NT%' and name in (select name from #TempUsers) -- SET RECOVERY MODE TO SIMPLE insert #Commands(Cmd) SELECT 'USE master; ALTER DATABASE '+QUOTENAME(@DatabaseName)+' SET RECOVERY SIMPLE WITH NO_WAIT' + ';' SELECT Cmd FROM #Commands -- IF OBJECT_ID('tempdb..#DatabaseLogins') IS NOT NULL DROP TABLE #DatabaseLogins -- IF OBJECT_ID('tempdb..#TempUsers') IS NOT NULL DROP TABLE #TempUsers -- IF OBJECT_ID('tempdb..#Commands') IS NOT NULL DROP TABLE #Commands ERROR: -- select * from #TempUsers

Comments

Page 192 of 211

Issue 202: /* This Script will Grant alter on all SP to a user or AD-Group to a specific database */ Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-Oct-12 Login_User_Schema

G(0)

Description /* This Script will Grant alter on all SP to a user or AD-Group to a specific database */
set nocount on go Declare @name varchar(500) Declare @message varchar(1000) DECLARE sp_exec CURSOR FOR select [name] from sysobjects where xtype = 'P' OPEN sp_exec WHILE @@FETCH_STATUS = 0 BEGIN FETCH NEXT FROM sp_exec into @name select @message = 'Grant alter on [' + @name + '] to [DHC\APP-EMCSourceOne-Security]' Print @message print 'go' END go CLOSE sp_exec go DEALLOCATE sp_exec go set nocount off

Comments

Page 193 of 211

Issue 203: /* This Script will Grant alter on all Table to a user or AD-Group to a specific database */ Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-Oct-12 Login_User_Schema

G(0)

Description /* This Script will Grant alter on all Table to a user or AD-Group to a specific database */
set nocount on go Declare @name varchar(500) Declare @message varchar(1000) DECLARE sp_exec CURSOR FOR select [name] from sysobjects where xtype = 'U' OPEN sp_exec WHILE @@FETCH_STATUS = 0 BEGIN FETCH NEXT FROM sp_exec into @name select @message = 'Grant alter on [' + @name + '] to [DHC\APP-EMCSourceOne-Security]' Print @message print 'go' END go CLOSE sp_exec go DEALLOCATE sp_exec go set nocount off

Comments

Page 194 of 211

Issue 204: Access given to the database. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 25-Oct-12 Login_User_Schema

G(0)

Description

SELECT ROL.name AS RoleName ,MEM.name AS MemberName ,MEM.type_desc AS MemberType ,MEM.default_schema_name AS DefaultSchema ,SP.name AS ServerLogin FROM sys.database_role_members AS DRM INNER JOIN sys.database_principals AS ROL ON DRM.role_principal_id = ROL.principal_id INNER JOIN sys.database_principals AS MEM ON DRM.member_principal_id = MEM.principal_id INNER JOIN sys.server_principals AS SP ON MEM.[sid] = SP.[sid] ORDER BY RoleName ,MemberName;
Comments

Page 195 of 211

Issue 206: Create non Interactive Windows Login from Windows- Create user -- data_reader and data_writer and grant execute. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 26-Oct-12 Login_User_Schema

G(0)

Description USE [master] GO CREATE LOGIN [DHC\svDSSLS] FROM WINDOWS WITH DEFAULT_DATABASE=[tempdb] GO
use SNL_trn go CREATE USER [DHC\svDSSLS] FOR LOGIN [DHC\svDSSLS] go exec sp_addrolemember N'db_datareader', 'DHC\svDSSLS' go exec sp_addrolemember N'db_datawriter', 'DHC\svDSSLS' use [snl_trn] GO GRANT EXECUTE TO [DHC\svDSSLS] GO

Comments

Page 196 of 211

Issue 207: Query to know unsent log size in mirroring Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 26-Oct-12 Mirroring

G(0)

Description
SET NOCOUNT ON DECLARE @dbname varchar(100),@vsql varchar(1000) DECLARE mirror_cursor CURSOR READ_ONLY for SELECT db_name(database_id) [DBName] FROM master.sys.database_mirroring WHERE mirroring_guid is not null OPEN mirror_cursor FETCH NEXT FROM mirror_cursor INTO @dbname WHILE @@FETCH_STATUS = 0 BEGIN SET @vsql=NULL SET @vsql='EXEC msdb.dbo.sp_dbmmonitorresults @database_name = ' + CHAR(39)+ @dbname + CHAR(39) EXEC (@vsql) FETCH NEXT FROM mirror_cursor INTO @dbname END CLOSE mirror_cursor DEALLOCATE mirror_cursor GO

Comments

Page 197 of 211

Issue 208: MSFOREACHDB All Schenrio Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 26-Oct-12 Database Property

G(0)

Description
sp_MSforeachdb 'USE ?; PRINT DB_NAME()' sp_MSforeachdb 'USE ? SELECT OBJECT_NAME(object_Id) FROM sys.tables where DB_NAME() NOT IN(''master'', ''model'', ''msdb'', ''tempdb'') sp_MSforeachdb 'USE ?; EXEC sp_spaceused' EXEC sp_MSforeachdb 'USE ? EXEC sp_helpfile;' sp_MSforeachdb 'DBCC CHECKDB(?)' -------------------------------------------------------------------------sp_MSforeachdb 'USE ?; SELECT a.FILEID,CONVERT(decimal(12,2),ROUND(a.size/128.000,2)) as [FILESIZEINMB] , CONVERT(decimal(12,2),ROUND(fileproperty(a.name,''SpaceUsed'')/128.000,2)) as [SPACEUSEDINMB], CONVERT(decimal(12,2),ROUND((a.size-fileproperty(a.name,''SpaceUsed''))/128.000,2)) as [FREESPACEINMB], a.name as [DATABASENAME],a.FILENAME as [FILENAME] FROM dbo.sysfiles a'

Comments

Page 198 of 211

Issue 209: How to Create Role - Grant Permission(Execute/Create table) to the role and adding the ROLE to Windows group. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 29-Oct-12 Login_User_Schema

G(0)

Description Use S1_Prod_Activity Go CREATE ROLE [db_exec] AUTHORIZATION [dbo] go GRANT EXECUTE TO [db_exec] GO exec sp_addrolemember N'db_exec',N'DHC\APP-EMC-Sourceone-Admin'; GO exec sp_addrolemember N'db_exec',N'DHC\APP-EMC-Sourceone-Security'; GO

USE [S1_Prod_Archive] Go CREATE ROLE [db_exec] AUTHORIZATION [dbo] GO GRANT EXECUTE TO [db_exec] GO exec sp_addrolemember N'db_exec',N'DHC\APP-EMC-Sourceone-Admin'; GO exec sp_addrolemember N'db_exec',N'DHC\APP-EMC-Sourceone-Security'; GO

USE [S1_Prod_DiscManager] GO CREATE ROLE [db_exec] AUTHORIZATION [dbo] GO GRANT EXECUTE TO [db_exec] GO exec sp_addrolemember N'db_exec',N'DHC\APP-EMC-Sourceone-Admin'; GO exec sp_addrolemember N'db_exec',N'DHC\APP-EMC-Sourceone-Security'; GO

USE [S1_Prod_Search] GO CREATE ROLE [db_exec] AUTHORIZATION [dbo] GO GRANT EXECUTE TO [db_exec] GO exec sp_addrolemember N'db_exec',N'DHC\APP-EMC-Sourceone-Admin'; GO exec sp_addrolemember N'db_exec',N'DHC\APP-EMC-Sourceone-Security'; GO

Comments
Page 199 of 211

Issue 210: Blocking Monitoring Query. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 06-Nov-12 Blocking query

G(0)

Description

SELECT dm_ws.wait_duration_ms, dm_ws.wait_type, dm_es.status, dm_t.TEXT, dm_qp.query_plan, dm_ws.session_ID, dm_es.cpu_time, dm_es.memory_usage, dm_es.logical_reads, dm_es.total_elapsed_time, dm_es.program_name, DB_NAME(dm_r.database_id) DatabaseName, -- Optional columns dm_ws.blocking_session_id, dm_r.wait_resource, dm_es.login_name, dm_r.command, dm_r.last_wait_type FROM sys.dm_os_waiting_tasks dm_ws INNER JOIN sys.dm_exec_requests dm_r ON dm_ws.session_id = dm_r.session_id INNER JOIN sys.dm_exec_sessions dm_es ON dm_es.session_id = dm_r.session_id CROSS APPLY sys.dm_exec_sql_text (dm_r.sql_handle) dm_t CROSS APPLY sys.dm_exec_query_plan (dm_r.plan_handle) dm_qp WHERE dm_es.is_user_process = 1 GO
Comments

Page 200 of 211

Issue 211: All Access for specific login to Database server across all database using sp_MSforeachDB Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 07-Nov-12 Login_User_Schema

G(0)

Description
DECLARE @UserName VARCHAR(128) SELECT @UserName = 'dhc\svcdvmp' DECLARE @DBRoles TABLE ( [Database Name] SYSNAME, [User Name] SYSNAME, [Role Name] SYSNAME ) DECLARE @DBPermissions TABLE ( [Database Name] SYSNAME NULL, [User Name] SYSNAME NULL, [Object Class] SYSNAME NULL, [Object Name] SYSNAME NULL, [Permission Type] VARCHAR(128) NULL, [Permission State] VARCHAR(128) NULL ) INSERT INTO @DBRoles EXEC ('sp_MSforeachDB '' USE [?] SELECT ''''?'''', MPI.name, RPI.name FROM sys.database_role_members RM JOIN sys.database_principals RPI ON RM.role_principal_id = RPI.principal_id JOIN sys.database_principals MPI ON RM.member_principal_id = MPI.principal_id WHERE MPI.name = ''''' + @UserName + '''''''') INSERT INTO @DBPermissions EXEC ('sp_MSforeachDB ''USE [?]; SELECT ''''?'''' AS [Database Name], DPri.[name] [User Name], DPer.class_desc [Object Class], object_name(major_id) [Object Name], DPer.permission_name [Permission Type], DPer.[state_desc] [Permission State] FROM sys.database_permissions DPer JOIN sys.database_principals DPri ON DPer.grantee_principal_id = DPri.principal_id WHERE DPri.[name] = ''''' + @UserName + ''''' ORDER BY DPri.[name]''') SELECT * FROM @DBRoles SELECT * FROM @DBPermissions

Comments

Page 201 of 211

Issue 212: To Check VIEW SERVER STATE permission is given or not. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 07-Nov-12 Login_User_Schema

G(0)

Description SELECT sp.name FROM sys.server_principals sp WHERE EXISTS (SELECT * FROM sys.server_permissions perm WHERE perm.grantee_principal_id = sp.principal_id AND permission_name = 'VIEW SERVER STATE') Comments
Issue 245: sp_helpsubscription and sp_helpsubscription sp_reinitsubscription and Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 13-Aug-13 Replication Concept

G(0)

Description
use prd_pos_parm go sp_helpsubscription 'T9783_parm' sp_reinitsubscription EXEC sp_reinitsubscription @subscriber = 'T9783', @destination_db = 'prd_pos_parm', @publication = 'T9783_parm' GO

Comments

Page 202 of 211

Issue 246: Managing TempDB in SQL Server: TempDB Configuration Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 23-Aug-13 tempdb space related

G(0)

Description
http://blogs.msdn.com/b/sqlserverstorageengine/archive/2009/01/04/managing-tempdb-in-sql-servertempdb-configuration.aspx?Redirected=true

Comments Issue 247: How to Check Last Known Good Dbcc checkdb completed on my database. Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 26-Aug-13 in

G(0)

Description
DBCC DBINFO ('VideoarchiveSQL') WITH TABLERESULTS -- 2013-08-25 22:40:00.413 --look for dbi_dbccLastKnownGood

DBCC TRACEON (3604); GO -- page 9 is the boot page DBCC PAGE (VideoarchiveSQL, 1, 9, 3); GO

Comments

Page 203 of 211

Issue 248: Various TraceFlags Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 26-Aug-13 DBCC And various Trace Flags

G(0)

Description

T3609 -- Start SQL server but skip Tempdb T3608 -- For recover only master Database T3400 T3403 Dbcc checkdb('') with no_infomsgs,all_errormsgs T1118 -Allocation bottleneck issue detection. Recovery Backup Verbose login -- 3400 and 3403. http://victorisakov.files.wordpress.com/2011/10/sql_pass_summit_2011important_trace_flags_that_every_dba_should_know-victor_isakov.pdf
Comments

Page 204 of 211

Issue 249: ISFailoverReady-ISJoined-isSuspended-SuspendReasonDescCategory Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 29-Aug-13 AlwaysOn

G(0)

Description
exec sp_executesql N' select * into #tmpag_availability_groups from master.sys.availability_groups select group_id, replica_id,replica_server_name,availability_mode into #tmpdbr_availability_replicas from master.sys.availability_replicas select replica_id,group_database_id,database_name,is_database_joined,is_failover_ready into #tmpdbr_database_replica_cluster_states from master.sys.dm_hadr_database_replica_cluster_states select * into #tmpdbr_database_replica_states from master.sys.dm_hadr_database_replica_states select replica_id,role,is_local into #tmpdbr_availability_replica_states from master.sys.dm_hadr_availability_replica_states select ars.role, drs.database_id, drs.replica_id, drs.last_commit_time into #tmpdbr_database_replica_states_primary_LCT from #tmpdbr_database_replica_states as drs left join #tmpdbr_availability_replica_states ars on drs.replica_id = ars.replica_id where ars.role = 1 SELECT AR.replica_server_name AS [AvailabilityReplicaServerName], dbcs.database_name AS [AvailabilityDatabaseName], CASE dbcs.is_failover_ready WHEN 1 THEN 0 ELSE ISNULL(DATEDIFF(ss, dbr.last_commit_time, dbrp.last_commit_time), 0) END AS [EstimatedDataLoss], CASE when ISNULL(dbcs.is_failover_ready,0) = 1 THEN ''Ready For Fail over '' ELSE ''Not Ready For Fail over'' END AS [IsFailoverReady], CASE WHEN ISNULL(dbcs.is_database_joined, 0) =1 Then ''Yes this database is joined/resumed'' ELSE ''No this database is not Joined or suspended'' END AS [IsJoined], CASE WHEN arstates.is_local =1 Then ''The database is local to the server instance'' ELse ''The database is not local to the SQL Server instance.'' END AS [IsLocal], ISNULL(dbr.is_suspended, 0) AS [IsSuspended], dbr.database_state_desc as Database_State_desc, dbr.suspend_reason_desc AS [SuspendReason_desc], ISNULL(CASE dbr.log_send_rate WHEN 0 THEN -1 ELSE CAST(dbr.log_send_queue_size AS float) / dbr.log_send_rate END, -1) AS [SynchronizationPerformance], ISNULL(dbr.synchronization_state, 0) AS [SynchronizationState] --ISNULL(dbr.truncation_lsn, 0) AS [TruncationLSN] FROM #tmpag_availability_groups AS AG INNER JOIN #tmpdbr_availability_replicas AS AR ON AR.group_id=AG.group_id INNER JOIN #tmpdbr_database_replica_cluster_states AS dbcs ON dbcs.replica_id = AR.replica_id LEFT OUTER JOIN #tmpdbr_database_replica_states AS dbr ON dbcs.replica_id = dbr.replica_id AND dbcs.group_database_id = dbr.group_database_id LEFT OUTER JOIN #tmpdbr_database_replica_states_primary_LCT AS dbrp ON dbr.database_id = dbrp.database_id INNER JOIN #tmpdbr_availability_replica_states AS arstates ON arstates.replica_id = AR.replica_id WHERE (AG.name=@_msparam_0) ORDER BY [AvailabilityReplicaServerName] ASC,[AvailabilityDatabaseName] ASC

Page 205 of 211

DROP TABLE #tmpdbr_availability_replicas DROP TABLE #tmpdbr_database_replica_cluster_states DROP TABLE #tmpdbr_database_replica_states DROP TABLE #tmpdbr_database_replica_states_primary_LCT DROP TABLE #tmpdbr_availability_replica_states drop table #tmpag_availability_groups ',N'@_msparam_0 nvarchar(4000)',@_msparam_0=N'SQL0043DAG01'

Comments

Page 206 of 211

Issue 250: *******Checking the Head Blocker*********** Very Good Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 04-Sep-13 Blocking query

G(0)

Description

SET NOCOUNT ON SET CONCAT_NULL_YIELDS_NULL OFF GO SELECT SPID, BLOCKED, REPLACE (REPLACE (T.TEXT, CHAR(10), ' '), CHAR (13), ' ' ) AS BATCH INTO #T FROM SYS.SYSPROCESSES R CROSS APPLY SYS.DM_EXEC_SQL_TEXT(R.SQL_HANDLE) T GO WITH BLOCKERS (SPID, BLOCKED, LEVEL, BATCH) AS ( SELECT SPID, BLOCKED, CAST (REPLICATE ('0', 4-LEN (CAST (SPID AS VARCHAR))) + CAST (SPID AS VARCHAR) AS VARCHAR (1000)) AS LEVEL, BATCH FROM #T R WHERE (BLOCKED = 0 OR BLOCKED = SPID) AND EXISTS (SELECT * FROM #T R2 WHERE R2.BLOCKED = R.SPID AND R2.BLOCKED <> R2.SPID) UNION ALL SELECT R.SPID, R.BLOCKED, CAST (BLOCKERS.LEVEL + RIGHT (CAST ((1000 + R.SPID) AS VARCHAR (100)), 4) AS VARCHAR (1000)) AS LEVEL, R.BATCH FROM #T AS R INNER JOIN BLOCKERS ON R.BLOCKED = BLOCKERS.SPID WHERE R.BLOCKED > 0 AND R.BLOCKED <> R.SPID ) SELECT N' ' + REPLICATE (N'| ', LEN (LEVEL)/4 - 2) + CASE WHEN (LEN (LEVEL)/4 1) = 0 THEN 'HEAD - ' ELSE '|------ ' END + CAST (SPID AS NVARCHAR (10)) + ' ' + BATCH AS BLOCKING_TREE FROM BLOCKERS ORDER BY LEVEL ASC GO DROP TABLE #T GO
Comments

Page 207 of 211

Issue 251: AlwaysOn Dashboard By sameer Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 04-Sep-13 AlwaysOn

G(0)

Description
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET NOCOUNT ON GO With AlwaysOnAGDeatils as ( select [Database_Name] , [Database_ID] , [AG_Name] , [DB_DataState] , [Current_Primary_Node] , [Current_Secondary_Node] , [DB_Sync_State] , [DB_State] , [AG_JoinState] , [DB_FailOver_Ready]

= = = = = = = = = =

, , , , , , , from

[Primary_Recovery_Health] [Sync_Health] [Availability_Mode] [Failover_Mode] [Session_Timeout_secs] [Read_Only_Routing_Set] [Backup_Preferred_Node]

= = = = = = =

dc.database_name DB_ID (dc.database_name) UPPER(ag.name) DATABASEPROPERTYEX(dc.database_name,'updateability') ags.primary_replica sar.replica_server_name drs.synchronization_state_desc drs.database_state_desc arc.join_state_desc CASE rcs.is_failover_ready WHEN 1 THEN 'IN_SYNC_READY' WHEN 0 THEN 'NO_SYNC_NOT_READY' END COALESCE(ags.primary_recovery_health_desc,'N/A') ags.synchronization_health_desc ar.availability_mode_desc ar.failover_mode_desc ar.session_timeout ar.read_only_routing_url UPPER(ag.automated_backup_preference_desc)

sys.availability_databases_cluster dc left join sys.availability_groups ag on dc.group_id = ag.group_id left join sys.dm_hadr_availability_group_states ags on ag.group_id = ags.group_id left join sys.availability_replicas ar on ag.group_id = ar.group_id and ar.replica_metadata_id IS NOT NULL left join sys.availability_replicas sar on ag.group_id = sar.group_id and sar.replica_metadata_id IS NULL left join sys.dm_hadr_availability_replica_cluster_states arc on ar.replica_id = arc.replica_id left join sys.dm_hadr_database_replica_cluster_states rcs on ar.replica_id = rcs.replica_id left join sys.dm_hadr_database_replica_states drs on ar.replica_id = drs.replica_id and drs.database_state_desc IS NOT NULL and rcs.group_database_id = drs.group_database_id ) select distinct AlwaysOnAGDeatils.[Database_Name] , AlwaysOnAGDeatils.[Database_ID] , AlwaysOnAGDeatils.[AG_Name] , AlwaysOnAGDeatils.[DB_DataState] , AlwaysOnAGDeatils.[Current_Primary_Node] , AlwaysOnAGDeatils.[Current_Secondary_Node] , AlwaysOnAGDeatils.[DB_Sync_State] , AlwaysOnAGDeatils.[DB_State] , AlwaysOnAGDeatils.[AG_JoinState] , AlwaysOnAGDeatils.[DB_FailOver_Ready] , AlwaysOnAGDeatils.[Primary_Recovery_Health] , AlwaysOnAGDeatils.[Sync_Health] , AlwaysOnAGDeatils.[Availability_Mode] , AlwaysOnAGDeatils.[Failover_Mode]

Page 208 of 211

, , , from

AlwaysOnAGDeatils.[Session_Timeout_secs] AlwaysOnAGDeatils.[Read_Only_Routing_Set] AlwaysOnAGDeatils.[Backup_Preferred_Node]

AlwaysOnAGDeatils order by AlwaysOnAGDeatils.[Database_Name] GO

Comments

Page 209 of 211

Issue 252: KB Articles Category Status Priority Attachments (1) Category Active (2) Normal Assigned To Due Date Opened By Opened Date 10-Sep-13 support.microsoft.com

G(0)

Description
KB article number Description

2511963 (http://support.microsoft.com/kb/2511963/ ) FIX: Query stops responding in SQL Server 2008 or in SQL Server 2008 R2 if the query alters or stops an Extended Events session

2811842 (http://support.microsoft.com/kb/2811842/ ) FIX: Missing parameter panel of a drillthrough report when a top-level report contains hidden parameters or no parameters in SSRS 2008 R2 or SSRS 2012

2831478 (http://support.microsoft.com/kb/2831478/ ) FIX: Incorrect result or access violation when you run an MDX query against an SSAS 2012 or SSAS 2008 R2 database that has multiple data sources

2843467 (http://support.microsoft.com/kb/2843467/ ) FIX: "Internal error" when you run an MDX query after you run an UPDATE CUBE statement in SSAS 2012 or SSAS 2008 R2

2844210 (http://support.microsoft.com/kb/2844210/ ) FIX: The Remote Registry service crashes when an application tries to retrieve Performance Counter data from another computer

2848247 (http://support.microsoft.com/kb/2848247/ ) FIX: Slow performance when many connections to a database that run the same query together with different query options in SQL Server 2008 R2

2855755 (http://support.microsoft.com/kb/2855755/ ) FIX: Sys.master_files catalog view is updated incorrectly after you change the file growth settings for a database in SQL Server 2008 R2

2859713 (http://support.microsoft.com/kb/2859713/ ) FIX: "The decryption key is incorrect" error when you open a symmetric key that is encrypted by an asymmetric key in SQL Server 2008, SQL Server 2012 or SQL Server 2008 R2

2861939 (http://support.microsoft.com/kb/2861939/ ) FIX: Cannot uninstall, repair, add new features to, or add a new instance to SQL Server 2008 or SQL Server 2008 R2 in Windows 8

2866062

Page 210 of 211

(http://support.microsoft.com/kb/2866062/ ) FIX: Access violation when you use DTA to analyze a database that contains a partition table in SQL Server 2008 R2

2868348 (http://support.microsoft.com/kb/2868348/ ) FIX: Chart data cannot be updated when you use the Report Viewer Web Part to view the report in SSRS 2008 R2

2875690 (http://support.microsoft.com/kb/2875690/ ) FIX: Exceptions occur and SSAS crashes after you apply CU12 for SQL Server 2008 R2 SP1 or CU5 for SQL Server 2008 R2 SP2

2877204 (http://support.microsoft.com/kb/2877204/ ) FIX: Error 8985 when you run the "dbcc shrinkfile" statement by using the logical name of a file in SQL Server 2008 R2

Comments

Page 211 of 211

You might also like