Professional Documents
Culture Documents
---------------------------------------------1. Open command line and go the the path C:\Program Files (x86)\Microsoft SQL Se
rver\100\Tools\Binn\ (on a 64-bit SQL 2008 Reporting Services )
2. List the report servers currently in the database type the command
RSKeyMgmt -l
5. Type the command RSKeyMgmt -l to list to server and verify that the server ha
s been removed.
----------------------------------------------------------------------------Logshipping
update msdb..log_shipping_monitor_secondary
set last_restored_file = 'O:\Logshipping\ProjectFile\ProjectFile_20141223050001
.trn'
where secondary_server = 'SYD2KSSQL01\DRSYD'
and primary_server = 'SYD1KSSQL01'
and secondary_database = 'ProjectFile'
@state VARCHAR(30)
@DbMirrored INT
@DbId INT
@String VARCHAR(100)
@databases TABLE (DBid INT, mirroring_state_desc VARCHAR(30))
USE DatabaseName
Go
Grant SHOWPLAN to [username]
----------------------------Index Fragmentation:
SELECT OBJECT_NAME(ind.OBJECT_ID) AS TableName,
ind.name AS IndexName, indexstats.index_type_desc AS IndexType,
indexstats.avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) indexstats
INNER JOIN sys.indexes ind
ON ind.object_id = indexstats.object_id
AND ind.index_id = indexstats.index_id
WHERE indexstats.avg_fragmentation_in_percent > 30--You can specify the percent
as you want
ORDER BY indexstats.avg_fragmentation_in_percent DESC
SELECT
deqs.last_execution_time AS [Time],
dest.TEXT AS [Query]
FROM
sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
ORDER BY
deqs.last_execution_time DESC
--------------------------SET
RECOVERY simple,
PAGE_VERIFY CHECKSUM,
MULTI_USER,
ONLINE;
GO
----------------------- Bring all databses online when DBs are in Single user, Suspecy, Recovery pen
ding mode in SQL Server 2012
declare @dbname varchar(255);
DECLARE dbname_cursor CURSOR FOR
SELECT name--, database_id, create_date, STATE_DESC
FROM sys.databases
WHERE STATE_DESC in ('SINGLE_USER', 'SUSPECT', 'RECOVERY_PENDING');
OPEN dbname_cursor
FETCH NEXT FROM dbname_cursor
INTO @dbname
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Recovering "' + @dbname + '"...'
exec sp_resetstatus @dbname;
exec('alter database [' + @dbname + '] set emergency');
dbcc checkdb(@dbname)
dbcc checkdb(@dbname)
exec('alter database [' + @dbname + '] set single_user with rollback imm
ediate');
dbcc checkdb (@dbname, repair_allow_data_loss)
exec('alter database [' + @dbname + '] set multi_user');
dbcc checkdb (@dbname)
FETCH NEXT FROM dbname_cursor
INTO @dbname
END
CLOSE dbname_cursor;
DEALLOCATE dbname_cursor;
-------------Select @@servername
Go
sp_dropserver 'servername'
Go
sp_addserver 'Newservername',local
Go
select @@servername
Go
select * from sys.servers
Go
---sp_dropserver 'old_name', 'droplogins'
go
sp_addserver 'new_name', 'local'
go
----------------First You need to bring the databse offline:
1) ALTER DATABASE database_name SET OFFLINE
Then You need to point the full text catalog in question to the new path:
2) ALTER DATABASE database_name MODIFY FILE ( NAME = logical_name , FILENAME =
'new_path')
You can find the logical name
-- Return the logical file name.
SELECT name, physical_name AS CurrentLocation, state_desc, type_desc
FROM sys.master_files
WHERE database_id = DB_ID(N'database_name')
The type_desc column should reveal wich row you are looking for.
Last step is to bring the database online again
3) ALTER DATABASE database_name SET ONLINE
====
Another more radical option would be to remove the full-text catalog completely
and then re-add, and re-populate, but if it's a large catalog it can take quite
some time to repopulate from scratch.
----------------------Backup Info
-------------Machine Details
DECLARE @Result TABLE
(
LogDate DATETIME,
ProcessInfo NVARCHAR(MAX),
Text NVARCHAR(MAX)
)
INSERT @Result
EXEC
sys.xp_readerrorlog 0, 1, 'System Manufacturer', 'VMware'
IF EXISTS (SELECT * FROM @Result)
SELECT 'Virtual Server' AS Msg
ELSE
SELECT 'Physical Server' AS Msg
OBJECT_NAME(ips.object_id) AS table_name,
ips.index_type_desc,
ISNULL(i.name, ips.index_type_desc) AS index_name,
ISNULL(REPLACE(RTRIM(( SELECT
c.name + CASE WHEN c.is_identit
y = 1 THEN ' (IDENTITY)' ELSE '' END + CASE WHEN ic.is_descending_key = 0 THEN '
' ELSE ' DESC ' END
FROM
sys.index_columns ic
INNER JOIN sys.columns c
ON ic.object_id = c.o
bject_id
AND ic.column_i
d = c.column_id
WHERE
ic.object_id = ips.object_id
AND ic.index_id = ips
.index_id
AND ic.is_inclu
ded_column = 0
ORDER BY
ic.key_ordinal
FOR XML PATH(''))), ' ', ', '), ips.index_
type_desc) AS index_keys,
ips.record_count,
(ips.page_count / 128.0) AS space_used_in_MB,
ips.avg_page_space_used_in_percent,
CASE WHEN i.fill_factor = 0 THEN 100 ELSE i.fill_factor END AS fill
_factor,
8096 / (ips.max_record_size_in_bytes + 2.00) AS min_rows_per_page,
8096 / (ips.avg_record_size_in_bytes + 2.00) AS avg_rows_per_page,
8096 / (ips.min_record_size_in_bytes + 2.00) AS max_rows_per_page,
8096 * ((100 - (CASE WHEN i.fill_factor = 0 THEN 100.00 ELSE i.fill
_factor END)) / 100.00) / (ips.avg_record_size_in_bytes + 2.0000) AS defined_fre
e_rows_per_page,
8096 * ((100 - ips.avg_page_space_used_in_percent) / 100.00) / (ips
.avg_record_size_in_bytes + 2) AS actual_free_rows_per_page,
reads = ISNULL(ius.user_seeks, 0) + ISNULL(ius.user_scans, 0) + ISN
ULL(ius.user_lookups, 0),
writes = ISNULL(ius.user_updates, 0),
1.00 * (ISNULL(ius.user_seeks, 0) + ISNULL(ius.user_scans, 0) + ISN
ULL(ius.user_lookups, 0)) / ISNULL(CASE WHEN ius.user_updates > 0 THEN ius.user_
updates END, 1) AS reads_per_write
FROM
sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'SAMPLED')
ips
WHERE
ORDER BY
----------------------------------------Truncate tables100-03-1134857
----------------------------------------TempDB 100% Full
use tempdb
backup log tempdb with Truncate_Only
dbcc shrinkfile(templog, 0)
BACKUP LOG 'databasename' WITH NO_LOG
-------------------------------------EXEC msdb..sp_get_sqlagent_properties
-------------------------------------
- SQLAGENT.OUT properties
FREEPROCCACHE
DROPCLEANBUFFERS
FREESYSTEMCACHE ('ALL')
FREESESSIONCACHE
SHRINKFILE (TEMPDEV,1024)
Exec Sp_resetstatus
Yourdbname
, repair _allow_data_loss)
or
mstsc /v:00.00.00.00 /console
USE Archive_MAP;
GO
BACKUP DATABASE Archive_MAP TO DISK=N'\\fdyddsvr001\MPCSQLTEST\MTS7007\Archive_M
AP\Archive_MAP_Full_04032013.BAK'
N'\\fdyddsvr001\MPCSQLTEST\FDYRS276\FDYSQL33_PROD33\MAPLGLMart\MAPLGLMart_Full_0
4042013.BAK'
-----------------------------------------------------------------------------------------------------Kill Sessions - Sleeping
----------------------------------DECLARE @v_spid INT
DECLARE c_Users CURSOR
FAST_FORWARD FOR
SELECT SPID
FROM master..sysprocesses (NOLOCK)
WHERE spid>50
AND status='sleeping'
AND DATEDIFF(mi,last_batch,GETDATE())>=60
AND spid<>@@spid
OPEN c_Users
FETCH NEXT FROM c_Users INTO @v_spid
WHILE (@@FETCH_STATUS=0)
BEGIN
PRINT 'KILLing '+CONVERT(VARCHAR,@v_spid)+'...'
EXEC('KILL '+@v_spid)
FETCH NEXT FROM c_Users INTO @v_spid
END
CLOSE c_Users
DEALLOCATE c_Users
------------------------------------Owner of DTS Package:
1.Open Query Analyzer
2.Select MSDB database
3.SELECT DISTINCT [name], [id] FROM sysdtspackages
4.Run the following query after setting the correct package Name/ID:
exec sp_reassign_dtspackageowner @name='My Package', @id='B3DA332F-48A9-4E6B-AE
AE-058EA4E2793C', @newloginname='NewOwner'
----------------------------------------------Backup %
----------------
USE master
GO
SELECT
Percent_Complete,
Start_Time ,
Command,
b.Name AS DatabaseName, --Sometimes this will be "Main" as the databas
e will not be accesiable.
DATEADD(ms,estimated_completion_time,GETDATE()) AS RemainTime,
(estimated_completion_time/1000/60) AS MinutesToFinish
FROM sys.dm_exec_requests a
INNER JOIN sys.databases b
ON a.database_id = b.database_id
WHERE
Command like '%Restore%'
OR Command like '%Backup%'
AND Estimated_Completion_Time > 0
------------------------------------------------------------Port Number of SQL Server:
SELECT SERVERNAME = CONVERT(NVARCHAR(128),SERVERPROPERTY('SERVERNAME'))
,LOCAL_NET_ADDRESS AS 'IPAddressOfSQLServer'
,local_tcp_port AS 'PortNumber'
FROM SYS.DM_EXEC_CONNECTIONS WHERE SESSION_ID = @@SPID
-------------------------Error Log path:
Function Get-ErrorLogPath
{
Param([string]$SQLServer = "(local)")
try {
add-type -AssemblyName "Microsoft.SqlServer.Smo,
Version=10.0.0.0,
Culture=neutral,
PublicKeyToken=89845dcd8080cc91" -EA Stop }
catch {add-type -AssemblyName "Microsoft.SqlServer.Smo"}
$server = new-object ("Microsoft.SqlServer.Management.Smo.Server") $SQLServer
$server.ErrorLogPath
} #end function Get-ErrorLogPath
Compatability level:
ALTER DATABASE database_name
SET COMPATIBILITY_LEVEL = { 90 | 100 | 110 }
80 = SQL Server 2000
90 = SQL Server 2005
\\fdyddsvr001\MPCSQLPROD\MPS7090\PROD_ma_trade
---------------------------------------------------------------------USE [master]
GO
ALTER DATABASE [TESTDB] SET READ_ONLY WITH NO_WAIT
GO
Make Database Read/Write
USE [master]
GO
ALTER DATABASE [TESTDB] SET READ_WRITE WITH NO_WAIT
GO
----------------------------------------------------------------Delete all rows in table:
DELETE FROM MyTable
---------------------------------------Clean up registry traces of SQL Server
Regedit \ regedt32
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MSSQLServer
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer
------------------------------------------------SQL Server: Incorrect PFS free space information for page (1:xxxx) in object ID
xxxxxx:
We have a maintenance plan which is scheduled to run on weekly basis and checks
the database integrity for specified user databases in production instance.
I found above error in SQL Server log. Clearly from the error message we can sa
y that it s not the page corruption. There is a special page called PFS (Page Free
Space) which indicates the percentage of page full. It actually helps free spac
?
ALTER DATABASE <Corrupted_Table_DatabaseName>
SET SINGLE_USER
WITH ROLLBACK IMMEDIATE
4.
Run DBCC CHECKTABLE() on specific table / index
?
DBCC CHECKTABLE(<Corrupted_Table>) WITH ALL_ERRORMSGS;
5.
It will reproduce the
PFS
error.
6.
To fix this execute the below two statements one after other.
?
DBCC CHECKTABLE(<Corrupted_Table>,REPAIR_FAST) WITH ALL_ERRORMSGS;
GO
DBCC CHECKTABLE(<corrupted_table>,REPAIR_REBUILD) WITH ALL_ERRORMSGS;
7.
For most of the cases the problems must be fixed with above two checks.
8.
If not goahead and execute the below statement
?
DBCC CHECKTABLE(<Corrupted_Table>,REPAIR_ALLOW_DATA_LOSS) WITH ALL_ERRORMSGS;
9.
For first time it executes and completes with the same PFS error message.
10.
Re execute the step number 8, now this time it fix the issue and avoid the PFS e
rror.
11.
Put database in multi user mode
Memory issue is very common stress for DBA but SQL server 2008 introduce new DMV
which we can use to handle the issue quickly. Need to follow the below step to
resolve the issue quickly.
sys.dm_os_sys_memory This DMV was introduced in SQL Server 2008 with an intentio
n of making life easier for all those systems where monitoring memory usage was
a mandatory requirement due to the nature of deployment. The system_memory_state_
desc column output of this DMV has three common states:
? Available physical memory is high
? Available physical memory is low
? Physical memory usage is steady
Step 1
select * from sys.dm_os_sys_memory where system_memory_state_desc= Available physi
cal memory is low . We can use the script to get the notification whenever memory
use by SQL server high and take some proactive action before database stop respo
nse.
Step 2: If we are getting alert like that SQL server Available physical memory i
s low then we can run the below script to know which database using most memory
Memory Occupied by each Database
SELECT
(CASE WHEN ([is_modified] = 1) THEN
Dirty
ELSE Clean
END) AS
Page State ,
ELSE
substring(convert(varchar(15),active_start_date),1,4) + '/' +
substring(convert(varchar(15),active_start_date),5,2) + '/' +
substring(convert(varchar(15),active_start_date),7,2)
END,
'Start Time' = CASE len(active_start_time)
WHEN 1 THEN cast('00:00:0' + right(active_start_time,2) as char(
8))
WHEN 2 THEN cast('00:00:' + right(active_start_time,2) as char(8
))
WHEN 3 THEN cast('00:0'
+ Left(right(active_start_time,3),1)
+':' + right(active_start_time,2) as char
WHEN 4 THEN cast('00:'
+ Left(right(active_start_time,4),2)
+':' + right(active_start_time,2) as char
WHEN 5 THEN cast('0'
+ Left(right(active_start_time,5),1)
+':' + Left(right(active_start_time,4),2)
+':' + right(active_start_time,2) as char
WHEN 6 THEN cast(Left(right(active_start_time,6),2)
+':' + Left(right(active_start_time,4),2)
+':' + right(active_start_time,2) as char
(8))
(8))
(8))
(8))
END,
-active_start_time as 'Start Time',
CASE len(run_duration)
WHEN 1 THEN cast('00:00:0'
+ cast(run_duration as char) as char (8))
WHEN 2 THEN cast('00:00:'
+ cast(run_duration as char) as char (8))
WHEN 3 THEN cast('00:0'
+ Left(right(run_duration,3),1)
+':' + right(run_duration,2) as char (8))
WHEN 4 THEN cast('00:'
+ Left(right(run_duration,4),2)
+':' + right(run_duration,2) as char (8))
WHEN 5 THEN cast('0'
+ Left(right(run_duration,5),1)
+':' + Left(right(run_duration,4),2)
+':' + right(run_duration,2) as char (8))
WHEN 6 THEN cast(Left(right(run_duration,6),2)
+':' + Left(right(run_duration,4),2)
+':' + right(run_duration,2) as char (8))
END as 'Max Duration',
CASE(dbo.sysschedules.freq_subday_interval)
WHEN 0 THEN 'Once'
ELSE cast('Every '
+ right(dbo.sysschedules.freq_subday_interval,2)
+ ' '
+
CASE(dbo.sysschedules.freq_subday_type)
WHEN 1 THEN 'Once'
WHEN 4 THEN 'Minutes'
WHEN 8 THEN 'Hours'
END as char(16))
END as 'Subday Frequency'
FROM dbo.sysjobs
LEFT OUTER JOIN dbo.sysjobschedules
ON dbo.sysjobs.job_id = dbo.sysjobschedules.job_id
INNER JOIN dbo.sysschedules ON dbo.sysjobschedules.schedule_id = dbo.sysschedule
s.schedule_id
LEFT OUTER JOIN (SELECT job_id, max(run_duration) AS run_duration
FROM dbo.sysjobhistory
GROUP BY job_id) Q1
ON dbo.sysjobs.job_id = Q1.job_id
WHERE Next_run_time = 0
UNION
SELECT dbo.sysjobs.Name AS 'Job Name',
'Job Enabled' = CASE dbo.sysjobs.Enabled
WHEN 1 THEN 'Yes'
WHEN 0 THEN 'No'
END,
'Frequency' = CASE dbo.sysschedules.freq_type
WHEN 1 THEN 'Once'
WHEN 4 THEN 'Daily'
WHEN 8 THEN 'Weekly'
WHEN 16 THEN 'Monthly'
WHEN 32 THEN 'Monthly relative'
WHEN 64 THEN 'When SQLServer Agent starts'
END,
'Start Date' = CASE next_run_date
WHEN 0 THEN null
ELSE
substring(convert(varchar(15),next_run_date),1,4) + '/' +
substring(convert(varchar(15),next_run_date),5,2) + '/' +
substring(convert(varchar(15),next_run_date),7,2)
END,
'Start Time' = CASE len(next_run_time)
WHEN 1 THEN cast('00:00:0' + right(next_run_time,2) as char(8))
WHEN 2 THEN cast('00:00:' + right(next_run_time,2) as char(8))
WHEN 3 THEN cast('00:0'
+ Left(right(next_run_time,3),1)
+':' + right(next_run_time,2) as char (8))
WHEN 4 THEN cast('00:'
+ Left(right(next_run_time,4),2)
+':' + right(next_run_time,2) as char (8))
WHEN 5 THEN cast('0' + Left(right(next_run_time,5),1)
+':' + Left(right(next_run_time,4),2)
+':' + right(next_run_time,2) as char (8))
WHEN 6 THEN cast(Left(right(next_run_time,6),2)
+':' + Left(right(next_run_time,4),2)
+':' + right(next_run_time,2) as char (8))
END,
-next_run_time as 'Start Time',
CASE len(run_duration)
WHEN 1 THEN cast('00:00:0'
+ cast(run_duration as char) as char (8))
WHEN 2 THEN cast('00:00:'
+ cast(run_duration as char) as char (8))
WHEN 3 THEN cast('00:0'
+ Left(right(run_duration,3),1)
+':' + right(run_duration,2) as char (8))
WHEN 4 THEN cast('00:'
+ Left(right(run_duration,4),2)
+':' + right(run_duration,2) as char (8))
WHEN 5 THEN cast('0'
+ Left(right(run_duration,5),1)
+':' + Left(right(run_duration,4),2)
set nocount on
DECLARE @sql_string NVARCHAR(max)
DECLARE @table_Name sysname
---------------------/*
SCRIPT TO CHECK THE AVG_FRAGMENTATION_IN_PERCENT FROM DMV
STATS
TO EXECUTE REORGANIZE OR REBUILD
AVG_FRAGMENTATION_IN_PERCENT < 30 % EXECUTE REORGANIZE
AVG_FRAGMENTATION_IN_PERCENT > 30 % EXECUTE REBUILD
FOR ALL THE DATABASES AND ITS TABLES IN AN INSTANCE
THEN EXECUTE UPDATE STATISTICS FOR ALL THE DATABASES
*/
-LIST OF USER DATABASE NAMES
DECLARE @Database VARCHAR(255)
DM_DB_INDEX_PHYSICAL_
OPEN DatabaseCursor
FETCH NEXT FROM DatabaseCursor INTO @Database
WHILE @@FETCH_STATUS = 0
BEGIN
START ALTER REORGANIZE/REBUILD
DECLARE @objectid int;
DECLARE @indexid int;
DECLARE @partitioncount bigint;
DECLARE @schemaname nvarchar(130);
DECLARE @objectname nvarchar(130);
DECLARE @indexname nvarchar(130);
DECLARE @partitionnum bigint;
DECLARE @partitions bigint;
DECLARE @frag float;
DECLARE @command nvarchar(4000);
select tables and indexes from the sys.dm_db_index_physical_stats function
and convert 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.
WHILE (1=1)
BEGIN;
FETCH NEXT
FROM partitions
INTO @objectid, @indexid, @partitionnum, @frag;
IF @@FETCH_STATUS < 0 BREAK;
SELECT @objectname = QUOTENAME(o.name), @schemaname = QUOTENAME(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 = QUOTENAME(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 re
building.
IF @frag < 30.0
SET @command = N ALTER INDEX
+ @indexname + N ON + @schemaname + N . + @objectname +
N REORGANIZE';
IF @frag >= 30.0
SET @command = N ALTER INDEX
+ @indexname + N ON + @schemaname + N . + @objectname +
N REBUILD';
IF @partitioncount > 1
+ CAST(@partitionnum AS nvarchar(10));
To turn on this feature across the board for all databases for user "User1" you
can issue the following statement:
USE master
GO
GRANT VIEW ANY DEFINITION TO User1
To turn this feature on for a database and for all users that have public access
you can issue the following:
USE AdventureWorks
GO
GRANT VIEW Definition TO PUBLIC
If you want to grant access to only user "User1" of the database you can do the
following:
USE AdventureWorks
GO
GRANT VIEW Definition TO User1
To turn off this functionality you would issue the REVOKE command such as one of
the following:
USE master
GO
REVOKE VIEW ANY DEFINITION TO User1
-- or
USE AdventureWorks
GO
REVOKE VIEW Definition TO User1
If you want to see which users have this access you can issue the following in t
he database.
USE AdventureWorks
GO
sp_helprotect
---------------------------------------------SELECT total_worker_time/execution_count AS AvgCPU
, total_worker_time AS TotalCPU
, total_elapsed_time/execution_count AS AvgDuration
, total_elapsed_time AS TotalDuration
, (total_logical_reads+total_physical_reads)/execution_count AS AvgReads
, (total_logical_reads+total_physical_reads) AS TotalReads
, execution_count
, SUBSTRING(st.TEXT, (qs.statement_start_offset/2)+1
, ((CASE qs.statement_end_offset WHEN -1 THEN datalength(st.TEXT)
ELSE qs.statement_end_offset
END - qs.statement_start_offset)/2) + 1) AS txt
, 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 1 DESC
---------------------SELECT TOP 3
total_worker_time ,
execution_count ,
total_worker_time / execution_count AS [Avg CPU Time] ,
CASE WHEN deqs.statement_start_offset = 0
AND deqs.statement_end_offset = -1
THEN '-- see objectText column--'
ELSE '-- query --' + CHAR(13) + CHAR(10)
+ SUBSTRING(execText.text, deqs.statement_start_offset / 2,
( ( CASE WHEN deqs.statement_end_offset = -1
THEN DATALENGTH(execText.text)
ELSE deqs.statement_end_offset
END ) - deqs.statement_start_offset ) / 2)
END AS queryText
FROM sys.dm_exec_query_stats deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.plan_handle) AS execText
ORDER BY deqs.total_worker_time DESC ;
----------------------------SELECT getdate() as "RunTime", st.text, qp.query_plan, a.* FROM sys.dm_exec_requ
ests a CROSS APPLY sys.dm_exec_sql_text(a.sql_handle) as st CROSS APPLY sys.dm_e
xec_query_plan(a.plan_handle) as qp order by CPU_time desc
----------------------------SELECT TOP (25)
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 OPTION (RECOMPILE);
------------------------------------To list all currently running queries in SQL Server, use this code:
SELECT r.session_id,
s.host_name,
s.login_name,
s.original_login_name,
r.status,
r.command,
r.cpu_time,
r.total_elapsed_time,
t.text as Query_Text
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(sql_handle) t
INNER JOIN sys.dm_exec_sessions s ON r.session_id = s.session_id
GO
---------------------------------the database name the requests are executing against and blocking session ID for
blocked queries:
SELECT r.session_id,
r.blocking_session_id,
DB_NAME(r.database_id) AS Database_Name,
s.host_name,
s.login_name,
s.original_login_name,
r.status,
r.command,
r.cpu_time,
r.total_elapsed_time,
t.text as Query_Text
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(sql_handle) t
INNER JOIN sys.dm_exec_sessions s ON r.session_id = s.session_id
--------------------------------------------------------------------running queries that are blocked and session ID of blocking queries run the foll
owing code
SELECT r.session_id,
r.blocking_session_id,
DB_NAME(r.database_id) AS Database_Name,
s.host_name,
s.login_name,
s.original_login_name,
r.status,
r.command,
r.cpu_time,
r.total_elapsed_time,
t.text as Query_Text
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(sql_handle) t
INNER JOIN sys.dm_exec_sessions s ON r.session_id = s.session_id
WHERE r.blocking_session_id <> 0
GO
------------------------------------Find Currently executing Queries, Blocking, Waits, Statement, Procedure, CPU
SELECT s.session_id
,r.STATUS
,r.blocking_session_id 'blocked by'
,r.wait_type
,wait_resource
,r.wait_time / (1000.0) 'Wait Time (in Sec)'
,r.cpu_time
,r.logical_reads
,r.reads
,r.writes
,r.total_elapsed_time / (1000.0) 'Elapsed Time (in Sec)'
,Substring(st.TEXT, (r.statement_start_offset / 2) + 1, (
(
CASE r.statement_end_offset
WHEN - 1
THEN Datalength(st.TEXT)
ELSE r.statement_end_offset
END - r.statement_start_offset
) / 2
) + 1) AS statement_text
,Coalesce(Quotename(Db_name(st.dbid)) + N'.' + Quotename(Object_schema_name(
st.objectid, st.dbid)) + N'.' +
Quotename(Object_name(st.objectid, st.dbid)), '') AS command_text
,r.command
,s.login_name
,s.host_name
,s.program_name
,s.host_process_id
,s.last_request_end_time
,s.login_time
,r.open_transaction_count
FROM sys.dm_exec_sessions AS s
INNER JOIN sys.dm_exec_requests AS r ON r.session_id = s.session_id
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) AS st
WHERE r.session_id != @@SPID
ORDER BY r.cpu_time DESC
,r.STATUS
,r.blocking_session_id
,s.session_id
------------------------WITH Waits AS
(SELECT wait_type, wait_time_ms / 1000. AS wait_time_s,
100. * wait_time_ms / SUM(wait_time_ms) OVER() AS pct,
ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS rn
FROM sys.dm_os_wait_stats
WHERE wait_type NOT IN ('CLR_SEMAPHORE','LAZYWRITER_SLEEP','RESOURCE_QUEUE','SLE
EP_TASK'
,'SLEEP_SYSTEMTASK','SQLTRACE_BUFFER_FLUSH','WAITFOR', 'LOGMGR_QUEUE','CHECKPOIN
T_QUEUE'
,'REQUEST_FOR_DEADLOCK_SEARCH','XE_TIMER_EVENT','BROKER_TO_FLUSH','BROKER_TASK_S
TOP','CLR_MANUAL_EVENT'
,'CLR_AUTO_EVENT','DISPATCHER_QUEUE_SEMAPHORE', 'FT_IFTS_SCHEDULER_IDLE_WAIT'
,'XE_DISPATCHER_WAIT', 'XE_DISPATCHER_JOIN', 'SQLTRACE_INCREMENTAL_FLUSH_SLEEP')
)
SELECT W1.wait_type,
CAST(W1.wait_time_s AS DECIMAL(12, 2)) AS wait_time_s,
CASE WHEN I.ignore_dup_key = 1 THEN ' IGNORE_DUP_KEY = ON ' ELSE ' IGNORE_
DUP_KEY = OFF ' END + ',' +
CASE WHEN ST.no_recompute = 0 THEN ' STATISTICS_NORECOMPUTE = OFF ' ELSE '
STATISTICS_NORECOMPUTE = ON ' END + ',' +
-- default value
' DROP_EXISTING = ON ' + ','
-- default value
' ONLINE = OFF ' + ','
CASE WHEN I.allow_row_locks = 1 THEN ' ALLOW_ROW_LOCKS = ON ' ELSE ' ALLOW_
ROW_LOCKS = OFF ' END + ',' +
CASE WHEN I.allow_page_locks = 1 THEN ' ALLOW_PAGE_LOCKS = ON ' ELSE ' ALLO
W_PAGE_LOCKS = OFF ' END + ' ) ON [' +
DS.name + ' ] '
[CreateIndexScript]
FROM sys.indexes I
JOIN sys.tables T ON T.Object_id = I.Object_id
JOIN sys.sysindexes SI ON I.Object_id = SI.id AND I.index_id = SI.indid
JOIN (SELECT * FROM (
SELECT IC2.object_id , IC2.index_id ,
STUFF((SELECT ' , ' + C.name + CASE WHEN MAX(CONVERT(INT,IC1.is_descend
ing_key)) = 1 THEN ' DESC ' ELSE ' ASC ' END
FROM sys.index_columns IC1
JOIN Sys.columns C
ON C.object_id = IC1.object_id
AND C.column_id = IC1.column_id
AND IC1.is_included_column = 0
WHERE IC1.object_id = IC2.object_id
AND IC1.index_id = IC2.index_id
GROUP BY IC1.object_id,C.name,index_id
ORDER BY MAX(IC1.key_ordinal)
FOR XML PATH('')), 1, 2, '') KeyColumns
FROM sys.index_columns IC2
--WHERE IC2.Object_id = object_id('Person.Address') --Comment for all tables
GROUP BY IC2.object_id ,IC2.index_id) tmp3 )tmp4
ON I.object_id = tmp4.object_id AND I.Index_id = tmp4.index_id
JOIN sys.stats ST ON ST.object_id = I.object_id AND ST.stats_id = I.index_id
JOIN sys.data_spaces DS ON I.data_space_id=DS.data_space_id
JOIN sys.filegroups FG ON I.data_space_id=FG.data_space_id
LEFT JOIN (SELECT * FROM (
SELECT IC2.object_id , IC2.index_id ,
STUFF((SELECT ' , ' + C.name
A.[object_id]
, OBJECT_NAME(A.[object_id]) AS Table_Name
, A.Index_ID
, A.[Name] As Index_Name
, CAST(
Case
When A.type = 1 AND is_unique = 1 Then 'Create Uniqu
e Clustered Index '
When A.type = 1 AND is_unique = 0 Then 'Create Clust
ered Index '
When A.type = 2 AND is_unique = 1 Then 'Create Uniqu
e NonClustered Index '
When A.type = 2 AND is_unique = 0 Then 'Create NonCl
ustered Index '
End
+ quotename(A.[Name]) + ' On ' + quotename(S.name) + '.' + q
uotename(OBJECT_NAME(A.[object_id])) + ' ('
+ Stuff(
(
Select
',[' + COL_NAME(A.[object_id],C.column_i
d)
+ Case When C.is_descending_key = 1 Then
'] Desc' Else '] Asc' End
From
Where
sys.index_columns C WITH
Where
A.[Object_ID] = C.object
(NOLOCK)
_id
And A.Index_ID = C.Index
_ID
And C.is_included_column
= 1
Order by C.index_column_id Asc
For XML Path('')
)
,1,1,'') + ') '
,'') End
+ Case When A.has_filter = 1 Then 'Where ' + A.filter_defini
tion Else '' End
+ ' With (Drop_Existing = OFF, SORT_IN_TEMPDB = ON'
--when the same index exists you'd better to set the Drop_Ex
isting = ON
--SORT_IN_TEMPDB = ON is recommended but based on your own e
nvironment.
+ ', Fillfactor = ' + Cast(Case When fill_factor = 0 Then 10
0 Else fill_factor End As varchar(3))
+ Case When A.[is_padded] = 1 Then ', PAD_INDEX = ON' Else '
, PAD_INDEX = OFF' END
+ Case When D.[no_recompute] = 1 Then ', STATISTICS_NORECOMP
UTE = ON' Else ', STATISTICS_NORECOMPUTE = OFF' End
+ Case When A.[ignore_dup_key] = 1 Then ', IGNORE_DUP_KEY =
ON' Else ', IGNORE_DUP_KEY = OFF' End
+ Case When A.[ALLOW_ROW_LOCKS] = 1 Then ', ALLOW_ROW_LOCKS
= ON' Else ', ALLOW_ROW_LOCKS = OFF' END
+ Case When A.[ALLOW_PAGE_LOCKS] = 1 Then ', ALLOW_PAGE_LOCK
S = ON' Else ', ALLOW_PAGE_LOCKS = OFF' End
+ Case When P.[data_compression] = 0 Then ', DATA_COMPRESSIO
N = NONE'
When P.[data_compression] = 1 Then ', DATA_COMPRESSI
ON = ROW'
Else ', DATA_COMPRESSION = PAGE' End
+ ') On '
+ Case when C.type = 'FG' THEN quotename(C.name)
--------------------------------This script will help DBA's in scripting out all the existing
indexes(Clustered , Non-Clustered, Clustered with PK,
Clustered with Unique key, Non-Clustered with Unique Key etc.)
in a Database.Script will script the Partition Indexes which
exists on Partition Scheme,Primary Filegroup or on any Filegroup
In SQL Server 2008 there is no way to script a index with
Filegroup or Partition Scheme Name.
It seems to me as a BUG
as In SQL Server 2005 we can script the Index with Filegroup
and Partition Scheme Name.
Hope it will help lot of DBA's.
-------------------------------------------------------------/*
Code Developed By
: Mohd Sufian
Code Developed Date
: 14th Novermber 2009
Code Developed Country : India
*/
SET NOCOUNT ON
--------------------------------------------------------------DECLARE @vNumDBs
Int
DECLARE @vCount
Int
--Decalared Variable Index Info----------------------DECLARE @SchemaName
Varchar(MAX)
DECLARE @TableName
Varchar(MAX)
DECLARE @IndexName
Varchar(MAX)
DECLARE @IndexType
Varchar(MAX)
DECLARE @Index_Id
Varchar(MAX)
DECLARE @Is_Primary_Key
INT
DECLARE @Is_Unique_Key
INT
DECLARE @Data_Space_id
INT
--Declared Variable Included Column In Index---------DECLARE @ColName
VARCHAR(max)
DECLARE @Index_Column_id
INT
DECLARE @KeyOrdinalid
INT
DECLARE @partition_ordinal
INT
DECLARE @IsDescendingKey
INT
DECLARE @ColIncludedInPartitionFucntion VARCHAR(MAX)
--------------------------------------------------------Declare Storage Variable----------------------------DECLARE @Rowcount INT
DECLARE @Storage INT
DECLARE @IndexonFileGroup VARCHAR(MAX)
--------------------------------------------------------Declare Misleneous variables------------------------DECLARE @CommaSeprator VARCHAR(1)
------------------------------------------------------DECLARE @Object_Holder TABLE (TabID int IDENTITY(1,1) ,
TableName varchar(max),Schemaname varchar(max))
INSERT INTO @Object_Holder(TableName,Schemaname)
SELECT sys.objects.NAME AS TABLENAME,
SCHEMA_NAME(sys.objects.SCHEMA_ID) AS SCHEMANAME
from sys.objects
INNER JOIN sys.indexes ON
sys.objects.object_id = sys.indexes.object_id
and sys.indexes.type_desc!='HEAP'
GROUP BY sys.objects.name,
SCHEMA_NAME(sys.objects.SCHEMA_ID),sys.objects.type
HAVING (sys.objects.type='Und sys.objects.name<>'sysdiagrams sys.objects.name -and sys.objects.name='Test1T @vNumDBs = @@RowCount
SET @vCount = 1
While @vCount <= @vNumDBs
BEGIN
SELECT @SchemaName=Schemaname,@TableName=TableName
FROM @Object_Holder where TabID=@vCount
---Check for Indexes on Each Objects
DECLARE @vNumIndex
Int
DECLARE @vCountIndex
Int
Print '--Index Script for Object :::::'+@TableName
CREATE Table #Index_Info_Holder (Index_RowID INT IDENTITY(1,1),
Index_Name varchar(MAX),Index_Type varchar(MAX),Index_Id Int,
ObjectID INT,IsPrimaryKey INT,IsUnique INT,data_space_id INT)
INSERT INTO #Index_Info_Holder (Index_Name,Index_Type,Index_Id,
ObjectID,IsPrimaryKey,IsUnique,data_space_id)
SELECT name , type_desc ,index_id,object_id,is_primary_key,
is_unique,data_space_id FROM sys.indexes where
object_id=OBJECT_ID(@TableName) and type_desc!='HEAP'
--'CDS_BreakMaster')--(@TableName)
SET @vNumIndex = @@RowCount
SET @vCountIndex = 1
WHILE @vCountIndex <= @vNumIndex
BEGIN
SELECT @IndexName=Index_name ,@IndexType= Index_type ,
@Index_Id=index_id,@Is_Primary_Key=IsPrimaryKey,
@Is_Unique_Key=IsUnique,@Data_Space_id=data_space_id
FROM #Index_Info_Holder
where objectid=OBJECT_ID(@TableName)
and Index_RowID=@vCountIndex
If @IndexType='CLUSTERED' and @Is_Primary_Key=1 --OR
@IndexType='NON CLUSTERED' or
BEGIN
Print 'ALTER TABLE ' + '[' + @SchemaName + '].[' + @TableName +'] ' +
'ADD CONSTRAINT ['+@IndexName+']' +' PRIMARY KEY CLUSTE
RED '
Print '('
END
If @IndexType='NONCLUSTERED' and @Is_Unique_Key=1--OR @IndexType='NON CLU
STERED' or
BEGIN
Print 'ALTER TABLE ' + '[' + @SchemaName + '].[' + @TableName +'] '
+ 'ADD CONSTRAINT ['+@IndexName+']' +' UNIQUE NONCLUS
TERED '
Print '('
END
If @IndexType='NONCLUSTERED' and @Is_Unique_Key=0 and @Is_Primary_Key=0
BEGIN
Print 'CREATE NONCLUSTERED INDEX ['+@IndexName+'] ON' + ' [' + @SchemaName
+ '].['
+ @TableName + ']'
Print '('
END
If @IndexType='CLUSTERED' and @Is_Unique_Key=0 and @Is_Primary_Key=0
BEGIN
Print 'CREATE CLUSTERED INDEX ['+ @IndexName +'] ON' + ' [' + @SchemaName
+ '].['
+ @TableName + ']'
Print '('
END
---Columns Included in Index--
DECLARE @vNumIndexIncludedCol
Int
DECLARE @vCountIndexIncludedCol
Int
CREATE TABLE #Index_IncludedColumnInfo
(
Index_IncludedColumnRowID
INT IDENTITY(1,1),
Index_IncludedObjectId
INT,
Index_IncludedColName
Varchar(MAX),
Index_IncludedColID
INT,
Index_IncludedColKeyOrdinal
INT,
Index_IncludedColPartitionOrdinal
INT,
Index_IncludedColPartitionIsDescendingKey INT
)
INSERT INTO #Index_IncludedColumnInfo
(Index_IncludedObjectId,Index_IncludedColName,Index_IncludedColID,
Index_IncludedColKeyOrdinal,Index_IncludedColPartitionOrdinal,
Index_IncludedColPartitionIsDescendingKey)SELECT object_id,
COL_NAME(object_id(@TableName),column_id),index_column_id,
key_ordinal,partition_ordinal,is_descending_key FROM
sys.index_columns where Object_Id=object_id(@TableName)|
and index_id=@Index_Id and key_ordinal<>0--and Partition_ordinal!=1
SET @vNumIndexIncludedCol = @@RowCount
SET @vCountIndexIncludedCol = 1
WHILE @vCountIndexIncludedCol <= @vNumIndexIncludedCol
BEGIN
SELECT @ColName=Index_IncludedColName,@Index_Column_id=Index_IncludedColID
,
@KeyOrdinalid=Index_IncludedColKeyOrdinal,
@partition_ordinal=Index_IncludedColPartitionOrdinal,
@IsDescendingKey=Index_IncludedColPartitionIsDescendingKey
FROM #Index_IncludedColumnInfo WHERE
Index_IncludedColumnRowID=@vCountIndexIncludedCol
and Index_IncludedColKeyOrdinal<>0
If @vCountIndexIncludedCol=@vNumIndexIncludedCol
--or @vCountIndexIncludedCol != @vNumIndexIncludedCol
BEGIN
SELECT @CommaSeprator=' '
END
If @vCountIndexIncludedCol<>@vNumIndexIncludedCol
--and @vCountIndexIncludedCol != @vCountIndexIncludedCol
BEGIN
SELECT @CommaSeprator=','
END
If @IsDescendingKey=0
BEGIN
Print '['+@ColName+'] ASC' + @CommaSeprator
END
If @IsDescendingKey=1
BEGIN
Print '['+@ColName+'] DESC'
END
SET @ColName=''
SET @vCountIndexIncludedCol = @vCountIndexIncludedCol + 1
END
SELECT @ColIncludedInPartitionFucntion=COL_NAME(object_id(@TableName),colu
mn_id)
FROM sys.index_columns where Object_Id=object_id(@TableName) and index_id=
@Index_Id
and Partition_ordinal=1
SELECT @Storage= Index_IncludedColPartitionOrdinal from #Index_IncludedCol
umnInfo
where Index_IncludedColPartitionOrdinal>0
Print ')'
If @IndexType='CLUSTERED' and @Is_Primary_Key=0 and @Is_Primary_Key=0
BEGIN
Print 'WITH (PAD_INDEX = ON, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPD
B = OFF,
IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80)'
END
If @IndexType='CLUSTERED' and @Is_Primary_Key=1
BEGIN
Print 'WITH (PAD_INDEX = ON, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPD
B = OFF,
IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80)'
END
If @IndexType='NONCLUSTERED' and @Is_Unique_Key=1--OR @IndexType='NON CLUST
ERED' or
BEGIN
Print 'WITH (PAD_INDEX = ON, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPD
B = OFF,
IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80)'
END
If @IndexType='NONCLUSTERED' and @Is_Unique_Key=0 and @Is_Primary_Key=0
BEGIN
PRINT 'WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = ON, SORT_IN_TEMPDB
= OFF,
IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_RO
W_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 70)'
END
SELECT @IndexonFileGroup=[name] FROM SYS.DATA_SPACES WHERE data_space_id=@
Data_Space_id
If @ColIncludedInPartitionFucntion IS NULL
BEGIN
SET @ColIncludedInPartitionFucntion=' '
END
If @ColIncludedInPartitionFucntion =''--IS NOT NULL
BEGIN
PRINT 'ON '+'['+@IndexonFileGroup+']'
--+ '(['+@ColIncludedInPartitionFucntion+'])'
END
If @ColIncludedInPartitionFucntion !=''
and @IndexonFileGroup<>'Primary'-- is not null --IS NOT NULL
BEGIN
PRINT 'ON '+'['+@IndexonFileGroup+']'+ '(['+@ColIncludedInPartitionFucnt
ion+'])'
END
If @ColIncludedInPartitionFucntion !=''
and @IndexonFileGroup='Primary'-- is not null --IS NOT NULL
BEGIN
PRINT 'ON '+'['+@IndexonFileGroup+']'--+ '(['+@ColIncludedInPartitionFuc
ntion+'])'
END
SET @Storage=''
DROP TABLE #Index_IncludedColumnInfo
Print '---------End of Index Script------------------------'
SET @vCountIndex = @vCountIndex + 1
END
DROP TABLE #Index_Info_Holder
--**********************************-SET @vCount = @vCount + 1
END
SET NOCOUNT OFF
--------------------------------------------------------------------------------------------------------------DECLARE
DECLARE
DECLARE
DECLARE
@Database VARCHAR(255)
@Table VARCHAR(255)
@cmd NVARCHAR(500)
@fillfactor INT
SET @fillfactor = 90
DECLARE DatabaseCursor CURSOR FOR
SELECT name FROM master.dbo.sysdatabases
WHERE name NOT IN ('master','msdb','tempdb','model','distribution')
ORDER BY 1
OPEN DatabaseCursor
FETCH NEXT FROM DatabaseCursor INTO @Database
WHILE @@FETCH_STATUS = 0
BEGIN
SET @cmd = 'DECLARE TableCursor CURSOR FOR SELECT ''['' + table_catalog + '']
.['' + table_schema + ''].['' +
table_name + '']'' as tableName FROM [' + @Database + '].INFORMATION_SCHEMA.TA
BLES
WHERE table_type = ''BASE TABLE'''
-- create table cursor
EXEC (@cmd)
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @Table
WHILE @@FETCH_STATUS = 0
BEGIN
IF (@@MICROSOFTVERSION / POWER(2, 24) >= 9)
BEGIN
-- SQL 2005 or higher command
SET @cmd = 'ALTER INDEX ALL ON ' + @Table + ' REBUILD WITH (FILLFACTO
R = ' + CONVERT(VARCHAR(3),@fillfactor) + ')'
EXEC (@cmd)
END
ELSE
BEGIN
-- SQL 2000 command
DBCC DBREINDEX(@Table,' ',@fillfactor)
END
FETCH NEXT FROM TableCursor INTO @Table
END
CLOSE TableCursor
DEALLOCATE TableCursor
----------------------------------------------------------------------------------DECLARE
DECLARE
DECLARE
DECLARE
@Database VARCHAR(255)
@Table VARCHAR(255)
@cmd NVARCHAR(500)
@fillfactor INT
SET @fillfactor = 90
DECLARE DatabaseCursor CURSOR FOR
SELECT name FROM master.dbo.sysdatabases
WHERE name NOT IN ('master','msdb','tempdb','model','distribution','MyCoatesHire
_Sitecore_Analytics','MyCoatesHire_Sitecore_Core','MyCoatesHire_Sitecore_Master'
,'MyCoatesHire_Sitecore_Web')
ORDER BY 1
OPEN DatabaseCursor
FETCH NEXT FROM DatabaseCursor INTO @Database
WHILE @@FETCH_STATUS = 0
BEGIN
SET @cmd = 'DECLARE TableCursor CURSOR FOR SELECT ''['' + table_catalog + '']
.['' + table_schema + ''].['' +
table_name + '']'' as tableName FROM [' + @Database + '].INFORMATION_SCHEMA.TA
BLES
WHERE table_type = ''BASE TABLE'''
-- create table cursor
EXEC (@cmd)
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @Table
WHILE @@FETCH_STATUS = 0
BEGIN
IF (@@MICROSOFTVERSION / POWER(2, 24) >= 9)
BEGIN
-- SQL 2005 or higher command
SET @cmd = 'ALTER INDEX ALL ON ' + @Table + ' REBUILD WITH (FILLFACTO
R = ' + CONVERT(VARCHAR(3),@fillfactor) + ')'
EXEC (@cmd)
END
ELSE
BEGIN
-- SQL 2000 command
DBCC DBREINDEX(@Table,' ',@fillfactor)
END
FETCH NEXT FROM TableCursor INTO @Table
END
CLOSE TableCursor
DEALLOCATE TableCursor
FETCH NEXT FROM DatabaseCursor INTO @Database
END
CLOSE DatabaseCursor
DEALLOCATE DatabaseCursor
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------Script to perform Index All Rebuild operation:
SET NOCOUNT ON
GO
--Determine if you want to execute the script with FULLSCAN
DECLARE @WithFullscan BIT
SELECT @WithFullscan = 1
--------------------Begin script
------------------DECLARE @StartTime DATETIME
SELECT @StartTime = GETDATE()
IF OBJECT_ID('tempdb..#TablesToUpdateStats') IS NOT NULL
BEGIN
DROP TABLE #TablesToUpdateStats
END
DECLARE @NumTables VARCHAR(20)
SELECT s.[Name] AS SchemaName
, t.[name] AS TableName
, SUM(p.rows) AS RowsInTable
INTO
#TablesToUpdateStats
FROM
sys.schemas s
LEFT JOIN sys.tables t
ON s.schema_id = t.schema_id
LEFT JOIN sys.partitions p
ON t.object_id = p.object_id
LEFT JOIN sys.allocation_units a
ON p.partition_id = a.container_id
WHERE p.index_id IN ( 0, 1 ) -- 0 heap table , 1 table with clustered inde
x
AND p.rows IS NOT NULL
AND a.type = 1 -- row-data only , not LOB
GROUP BY s.[Name]
, t.[name]
SELECT @NumTables = @@ROWCOUNT
DECLARE updatestats CURSOR
FOR
SELECT ROW_NUMBER() OVER ( ORDER BY ttus.RowsInTable )
, ttus.SchemaName
, ttus.TableName
, ttus.RowsInTable
FROM
#TablesToUpdateStats AS ttus
ORDER BY ttus.RowsInTable
OPEN updatestats
DECLARE
DECLARE
DECLARE
DECLARE
DECLARE
DECLARE
DECLARE
@TableNumber VARCHAR(20)
@SchemaName NVARCHAR(128)
@tableName NVARCHAR(128)
@RowsInTable VARCHAR(20)
@Statement NVARCHAR(300)
@Status NVARCHAR(300)
@FullScanSQL VARCHAR(20)
IF @WithFullscan = 1
BEGIN
SELECT @FullScanSQL = ' WITH FULLSCAN'
END
ELSE
BEGIN --If @WithFullscan<>1 then set @FullScanSQL to empty string
SELECT @FullScanSQL = ''
END
FETCH NEXT FROM updatestats INTO @TableNumber, @SchemaName, @tablename,
@RowsInTable
WHILE ( @@FETCH_STATUS = 0 )
BEGIN
SET @Statement = 'UPDATE STATISTICS [' + @SchemaName + '].['
+ @tablename + ']' + @FullScanSQL
SET @Status = 'Table ' + @TableNumber + ' of ' + @NumTables
+ ': Running ''' + @Statement + ''' (' + @RowsInTable
+ ' rows)'
RAISERROR (@Status, 0, 1) WITH NOWAIT --RAISERROR used to immediate
ly output status
EXEC sp_executesql @Statement
FETCH NEXT FROM updatestats INTO @TableNumber, @SchemaName,
@tablename, @RowsInTable
END
CLOSE updatestats
DEALLOCATE updatestats
DROP TABLE #TablesToUpdateStats
PRINT 'Total Elapsed Time: ' + CONVERT(VARCHAR(100), DATEDIFF(minute,
@StartTime,
GETDATE()))
+ ' minutes'
GO
-------------------------------------------------------
DECLARE
DECLARE
DECLARE
DECLARE
@databaseName sysname
@backupStartDate datetime
@backup_set_id_start INT
@backup_set_id_end INT