You are on page 1of 50

532369022

select @@SERVERNAME as Servername


Select @@version as SQLserverVersion
SELECT SERVERPROPERTY('productversion') as ProductVersion, SERVERPROPERTY ('prod
uctlevel') as ServicePack , SERVERPROPERTY ('edition') as Edition
SELECT
SERVERPROPERTY('ProductVersion') AS ProductVersion,
SERVERPROPERTY('ProductLevel') AS ProductLevel,
SERVERPROPERTY('Edition') AS Edition;
GO

RESTORE FILELISTONLY FROM DISK = 'C:\AdventureWorks.BAK' WITH FILE = 1


GO
SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVER
PROPERTY ('edition')
Select @@version
Recycle Error log:
EXEC sp_cycle_errorlog
GO
-----------------------------------TRIGGERS/CONSTRAINS Enable
exec sp_msforeachtable @command1="print '?'", @command2="ALTER TABLE ? WITH CHEC
K CHECK CONSTRAINT all"
exec sp_msforeachtable @command1="print '?'", @command2="ALTER TABLE ? ENABLE TR
IGGER all"
Disbale
sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
sp_msforeachtable "ALTER TABLE ? DISABLE TRIGGER all"

---------------------------------------------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

You will see the server listed with their GUID.


Note the GUID of the server that you want to remove.
3. To remove the instance of the Report server type the command below.
RSKeyMgmt -r GUIDoftheSSRSserverTobeRemoved
4. You will be prompted by a question if you're sure you want to do this. Press
Y if you're sure you want to remove the server.

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'

------------------------------------------------------SELECT CONVERT(DECIMAL(10,2),(SUM(size * 8.00) / 1024.00 / 1024.00)) As UsedSpac


e
FROM master.sys.master_files
--------------------Remove DB from DB mirroing
ALTER DATABASE [cph_b2b_idm] SET PARTNER OFF
SELECT * FROM sys.endpoints
WHERE type = 4
ALTER DATABASE [ca_b2b_sitecore_core] SET PARTNER TIMEOUT 2400

'DB Alert Script'


DECLARE
DECLARE
DECLARE
DECLARE
DECLARE

@state VARCHAR(30)
@DbMirrored INT
@DbId INT
@String VARCHAR(100)
@databases TABLE (DBid INT, mirroring_state_desc VARCHAR(30))

-- get status for mirrored databases


INSERT @databases
SELECT database_id, mirroring_state_desc
FROM sys.database_mirroring
WHERE mirroring_role_desc IN ('PRINCIPAL','MIRROR')
AND mirroring_state_desc NOT IN ('SYNCHRONIZED','SYNCHRONIZING')
-- iterate through mirrored databases and send email alert
WHILE EXISTS (SELECT TOP 1 DBid FROM @databases WHERE mirroring_state_desc IS NO
T NULL)
BEGIN
SELECT TOP 1 @DbId = DBid, @State = mirroring_state_desc
FROM @databases
SET @string = 'Host: '+@@servername+'.'+CAST(DB_NAME(@DbId) AS VARCHAR)+ ' - DB
Mirroring is '+@state +' - notify DBA'
EXEC msdb.dbo.sp_send_dbmail 'DBMAIL', 'mymail@company.com', @body = @string, @s
ubject = @string
DELETE FROM @databases WHERE DBid = @DbId
END
--also notify if there is no mirroring in case there should be mirroring
SELECT @DbMirrored = COUNT(*)
FROM sys.database_mirroring
WHERE mirroring_state IS NOT NULL
IF @DbMirrored = 0
BEGIN
SET @string = 'Host: '+@@servername+' - No databases are mirrored on this server
- notify DBA'
EXEC msdb.dbo.sp_send_dbmail 'DBMAIL', 'mymail@company.com', @body = @string, @s
ubject = @string
-----------------------Jobs History
SELECT sj.name,
sja.run_requested_date,
CONVERT(VARCHAR(12), sja.stop_execution_date-sja.start_execution_date, 1
14) Duration
FROM msdb.dbo.sysjobactivity sja
INNER JOIN msdb.dbo.sysjobs sj
ON sja.job_id = sj.job_id
WHERE sja.run_requested_date IS NOT NULL
ORDER BY sja.run_requested_date desc
--------------------------Permission to view Execution Plans in SQL Server.

Run below script to provide access permission to execution plans in database.

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 dbschemas.[name] as 'Schema',


dbtables.[name] as 'Table',
dbindexes.[name] as 'Index',
indexstats.avg_fragmentation_in_percent,
indexstats.page_count
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS indexst
ats
INNER JOIN sys.tables dbtables on dbtables.[object_id] = indexstats.[object_id]
INNER JOIN sys.schemas dbschemas on dbtables.[schema_id] = dbschemas.[schema_id]
INNER JOIN sys.indexes AS dbindexes ON dbindexes.[object_id] = indexstats.[objec
t_id]
AND indexstats.index_id = dbindexes.index_id
WHERE indexstats.database_id = DB_ID()
ORDER BY indexstats.avg_fragmentation_in_percent desc
--------------------Find all the queries running on SQL Server
SELECT sqltext.TEXT,
req.session_id,
req.status,
req.command,
req.cpu_time,
req.total_elapsed_time
FROM sys.dm_exec_requests req
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext
------------------------------Find all the queries executed recently on a database

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 sj.name as 'Job Name' from msdb..sysjobs sj left join master.sys.syslogin


s
Jobs:::
select s.name,l.name
from msdb..sysjobs s
left join master.sys.syslogins l on s.owner_sid = l.sid
Packages:::
select s.name,l.name
from msdb..sysssispackages s
left join master.sys.syslogins l on s.ownersid = l.sid
----------------------SELECT *
FROM sys.dm_os_schedulers
WHERE scheduler_id < 255;

-----------------EXEC sp_configure 'show advanced options', 1;


GO
RECONFIGURE WITH OVERRIDE;
GO
EXEC sp_configure 'max degree of parallelism', 8;
GO
RECONFIGURE WITH OVERRIDE;
GO
---------------------------Rename a DB
USE master
GO
ALTER DATABASE CoreDB
SET SINGLE_USER
WITH ROLLBACK IMMEDIATE
GO
EXEC master..sp_renamedb 'CoreDB','ProductsDB'
GO
ALTER DATABASE ProductsDB
SET MULTI_USER
GO

-------------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.

EXEC master.dbo.sp_detach_db @dbname = N'dbname', @keepfulltextindexfile=N'false


'
and attach datbase
----------------------declare @dbname sysname

declare c_loop cursor for


select name from sysdatabases
where sid <> 0x01
order by name
open c_loop
fetch next from c_loop into @dbname
while @@fetch_status <> -1 begin -- determines loop is continuing
if @@fetch_status <> -2 begin -- determines record is still available (not dirty
)
print 'use ' + @dbname
print 'g' + 'o'
print 'exec sp_changedbowner ''sa'''
print 'g' + 'o'
print ''
end
fetch next from c_loop into @dbname
end
close c_loop
deallocate c_loop

----------------------Backup Info

SELECT TOP 100


s.database_name,
m.physical_device_name,
CAST(CAST(s.backup_size / 1000000 AS INT) AS VARCHAR(14)) + ' ' + 'MB' AS bkSize
,
CAST(DATEDIFF(second, s.backup_start_date,
s.backup_finish_date) AS VARCHAR(4)) + ' ' + 'Seconds' TimeTaken,
s.backup_start_date,
CAST(s.first_lsn AS VARCHAR(50)) AS first_lsn,
CAST(s.last_lsn AS VARCHAR(50)) AS last_lsn,
CASE s.[type]
WHEN 'D' THEN 'Full'
WHEN 'I' THEN 'Differential'
WHEN 'L' THEN 'Transaction Log'
END AS BackupType,
s.server_name,
s.recovery_model
FROM msdb.dbo.backupset s
INNER JOIN msdb.dbo.backupmediafamily m ON s.media_set_id = m.media_set_id
WHERE s.database_name = DB_NAME() -- Remove this line for all the database
ORDER BY backup_start_date DESC, backup_finish_date
GO

-------------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

---------------------------Fill Factor recomendations:


SELECT

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

INNER JOIN sys.indexes i


ON ips.object_id = i.object_id
AND ips.index_id = i.index_id
LEFT OUTER JOIN sys.dm_db_index_usage_stats ius
ON ius.database_id = DB_ID()
AND ips.object_id = ius.object_id
AND ips.index_id = ius.index_id
ips.alloc_unit_type_desc != 'LOB_DATA'
ips.index_type_desc,
OBJECT_NAME(ips.object_id),
(ips.page_count / 128.0)

----------------------------------------------------------------------EXEC sp_changedbowner 'Emil'


Exec Sp_readerrorlog
------------------------------------Number of connections
SELECT
DB_NAME(dbid) as DBName,
COUNT(dbid) as NumberOfConnections,
loginame as LoginName
FROM
sys.sysprocesses
WHERE
dbid > 0
GROUP BY
dbid, loginame

----------------------------------------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

BACKUP LOG TempDB WITH NO_LOG.


dbcc shrinkfile(templog, 0)
----------------------------Temp DB without restart
DBCC
GO
DBCC
go
DBCC
GO
DBCC
GO
DBCC
Go

FREEPROCCACHE
DROPCLEANBUFFERS
FREESYSTEMCACHE ('ALL')
FREESESSIONCACHE
SHRINKFILE (TEMPDEV,1024)

----------------------------Long Running Queries


SELECT TOP 10
ObjectName
= OBJECT_NAME(qt.objectid)
,DiskReads
= qs.total_physical_reads -- The worst reads, disk reads
,MemoryReads
= qs.total_logical_reads --Logical Reads are memory reads
,Executions
= qs.execution_count
,AvgDuration
= qs.total_elapsed_time / qs.execution_count
,CPUTime
= qs.total_worker_time
,DiskWaitAndCPUTime = qs.total_elapsed_time
,MemoryWrites
= qs.max_logical_writes
,DateCached
= qs.creation_time
,DatabaseName
= DB_Name(qt.dbid)
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt
WHERE qt.dbid = db_id() -- Filter by current database
ORDER BY qs.total_elapsed_time DESC
------------------------------------------------------------------------------Emergency Mode
----------

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


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

-select count(*) from sys.dm_exec_requests where db_name(database_id) = 'MyDataba


seName'
- No of Users Connected

SELECT COUNT(DISTINCT spid)


FROM master.dbo.sysprocesses
WHERE spid >= 50
AND dbid = DB_ID('MyDBName')
-------------------------------------------------------------------------------------DBCC PAGE ('prodca_www_sitecore_master', 1, 6294, 1)
--------------------------EXEC master..xp_fixeddrives
select * from sysaltfiles where filename like '%map%'
select db_name (9)
dbcc sqlperf (logspace)
sp_helpfile
dbcc shrinkfile (2,5024)
--------------------------------------------select * from sysprocesses where blocked<>0
sp_who2 active
-------------------------------------------------dbcc inputbuffer(133)
kill 133
---------------------------------------------------alter database databasename set recovery simple;
DBCC CHECKDB ('AdventureWorks2008R2', REPAIR_ALLOW_DATA_LOSS);
The terminal server has exceeded the maximum number of allowed connections
To get around this, open a Command Prompt and type:
mstsc /v:00.00.00.00 /admin

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

100 = SQL Server 2008


select compatibility_level from sys.databases where name=db_name()
------------------------------------------------------------------------------------------------------------Integrity Job Fails:
---------------------EXEC sys.sp_configure N'user options', 0 RECONFIGURE

sp_configure 'Allow Updates', 0


-----------------------------------------------------------------------------------------------------------------Alter Database name:
----------------------select suser_sname(owner_sid) from sys.databases where name = 'Northwind'
-------------------------------------------------------------All logins in Server:
SELECT name FROM SYS.sysLogins WHERE sid IS NOT NULL

SELECT name FROM master..sysxlogins WHERE sid IS NOT NULL


------------------------------------------------------------Fix Orphan users:
----------------------------------EXEC sp_change_users_login 'Report'
If you already have a login id and password for this user, fix it by doing:
EXEC sp_change_users_login 'Auto_Fix', 'user'
If you want to create a new login id and password for this user, fix it by doing
:
EXEC sp_change_users_login 'Auto_Fix', 'user', 'login', 'password'
------------------------------------------------------------------------------------------------------------Unlock SQL user

------------------ALTER LOGIN sqluser WITH CHECK_POLICY = OFF;


ALTER LOGIN sqluser WITH CHECK_POLICY = ON;
GO
----------------------------------------------RESTORE FILELISTONLY FROM disk = 'E:\Restore_20130223\PROD_ma_trade_FULL_backup_
23022013.BAK'
-------------------------------------------------Lebanon (Production servers/site)
* (file://cylddsvr001/MPCSQLPROD)\\cylddsvr001\MPCSQLPROD (file://cylddsvr001/M
PCSQLPROD) - Place ALL Lebanon files here
* Replica of Findlay backup files located in \\cylddsvr001\MPCSQLTEST (file://
cylddsvr001/MPCSQLTEST) - Read only

----------------------------------Change the SQL Server Memory Setting on MPS6821 :


---------------------------------------Open SQL Server Management Studio of MPS6821 & execute the below script.
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'max server memory', 7168;
GO
RECONFIGURE;
GO
Other Method:
1. Open SQL Server Management Studio & Right clcik on Sever.
2. Select Memory & under the Memory options, enter the amount that you want for
Minimum server memory and Maximum server memory.
---------------------------------------

restore database PROD_ma_trade from disk='\\Mps7090\23022013_Backup\PROD_ma_trad


e_FULL_backup_23022013.BAK'
with stats=10,Recovery,
Move 'PROD_ma_trade_Data' to 'E:\Data\PROD_ma_trade.mdf',

Move 'PROD_ma_trade_Log' to 'T:\MSSQL\LOG1\PROD_ma_trade_Log1.ldf',


move 'PROD_ma_trade_Log2' to 'T:\MSSQL\LOG2\PROD_ma_trade_Log2.ldf'

\\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

---------------------Drop Failed for User.


select dp2.name as role, dp1.name as owner
from sys.database_principals as dp1 inner join sys.database_principals as dp2
on dp1.principal_id = dp2.owning_principal_id
where dp1.name = 'MGROUPNET\JC2'
freespace
----------------------declare @svrName varchar(255)
declare @sql varchar(400)
--by default it will take the current server name, we can the set the server na
me as well

set @svrName = @@SERVERNAME


set @sql = 'powershell.exe -c "Get-WmiObject -ComputerName ' + QUOTENAME(@svrNam
e,'''') + ' -Class Win32_Volume -Filter ''DriveType = 3'' | select name,capacity
,freespace | foreach{$_.name+''|''+$_.capacity/1048576+''%''+$_.freespace/104857
6+''*''}"'
--creating a temporary table
CREATE TABLE #output
(line varchar(255))
--inserting disk name, total space and free space value in to temporary table
insert #output
EXEC xp_cmdshell @sql
--script to retrieve the values in MB from PS Script output
select rtrim(ltrim(SUBSTRING(line,1,CHARINDEX('|',line) -1))) as drivename
,round(cast(rtrim(ltrim(SUBSTRING(line,CHARINDEX('|',line)+1,
(CHARINDEX('%',line) -1)-CHARINDEX('|',line)) )) as Float),0) as 'capacity
(MB)'
,round(cast(rtrim(ltrim(SUBSTRING(line,CHARINDEX('%',line)+1,
(CHARINDEX('*',line) -1)-CHARINDEX('%',line)) )) as Float),0) as 'freespac
e(MB)'
from #output
where line like '[A-Z][:]%'
order by drivename
--script to retrieve the values in GB from PS Script output
select rtrim(ltrim(SUBSTRING(line,1,CHARINDEX('|',line) -1))) as drivename
,round(cast(rtrim(ltrim(SUBSTRING(line,CHARINDEX('|',line)+1,
(CHARINDEX('%',line) -1)-CHARINDEX('|',line)) )) as Float)/1024,0) as 'ca
pacity(GB)'
,round(cast(rtrim(ltrim(SUBSTRING(line,CHARINDEX('%',line)+1,
(CHARINDEX('*',line) -1)-CHARINDEX('%',line)) )) as Float) /1024 ,0)as 'fr
eespace(GB)'
from #output
where line like '[A-Z][:]%'
order by drivename
--script to drop the temporary table
drop table #output

------------------------------------------------SQL Server: Incorrect PFS free space information for page (1:xxxx) in object ID
xxxxxx:

Incorrect PFS free space information for page (1:233791) in


object ID 367392428, index ID 1, partition ID 72057594180730880, alloc unit ID 7
2057594222018560 (type LOB data). Expected value 0_PCT_FULL, actual value 100_
PCT_FULL. CHECKDB found 0 allocation errors and 1 consistency errors in table xx
xxxxx (object ID 367392428).

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

e scanner while inserting data.


In this case PFS is 100% means it indicates page is full whereas in real the pag
e is empty. DBCC commands will fail due to this wrong calculation.
Resolution:
To resolve this I have tried the below procedure.
1.
Take a full backup of the database (Based on the size if it s a huge DB take the b
ackup of table just by using SELECT * INTO <bkp_table> FROM <corrupted_table>)
2.
From sql log we can find the object (Table/Index) name and ID
3.
Put database in single user mode

?
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

------------------------------------------Resolve the memory issue quickly at SQL server 2008

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

(CASE WHEN ([database_id] = 32767) THEN Resource Database


d) END) AS Database Name ,

Page State ,

ELSE DB_NAME (database_i

COUNT (*) AS Page Count


FROM sys.dm_os_buffer_descriptors
GROUP BY [database_id], [is_modified]
ORDER BY [database_id], [is_modified];
GO
Step 3: To freed up the memory we can use the below script together.
DBCC FREESYSTEMCACHE ( ALL ) WITH MARK_IN_USE_FOR_REMOVAL;
DBCC FREESESSIONCACHE WITH NO_INFOMSGS;
GO
DBCC DROPCLEANBUFFERS
DBCC FREEPROCCACHE;
-------------------------------------------------------------Agent Jobs History:
USE msdb
Go
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 active_start_date
WHEN 0 THEN null

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)

+':' + 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
ORDER BY [Start Date],[Start Time]
----------------------------------------------------------Build the list of Tables and indexes along with the DBCC string
DECLARE @TsAndIs TABLE (T_Name VARCHAR(500) NULL, I_Name VARCHAR(250) NULL)
INSERT INTO @TsAndIs (T_name, I_name)
SELECT 'DBCC INDEXDEFRAG (0,' + CAST(sysobjects.id AS VARCHAR) + ',' + sysindexe
s.name + ')',sysindexes.name FROM sysobjects INNER JOIN sysindexes
ON sysobjects.id = sysindexes.id
WHERE sysindexes.indid > 0 AND sysindexes.indid < 255 AND (sysindexes.status & 6
4)=0
AND sysobjects.xtype NOT IN ('S', 'PK', 'V', 'P','F','D') AND sysobjects.name <>
'dtproperties'
SELECT T_name from @TsAndIs
-----------------------------------------Index Stats

SELECT OBJECT_NAME(S.[OBJECT_ID]) AS [OBJECT NAME],


I.[NAME] AS [INDEX NAME], USER_SEEKS, USER_SCANS, USER_LOOKUPS, USER_UPDATES
FROM SYS.DM_DB_INDEX_USAGE_STATS AS S
INNER JOIN SYS.INDEXES AS I ON I.[OBJECT_ID] = S.[OBJECT_ID] AND I.INDEX_ID = S
.INDEX_ID
WHERE OBJECTPROPERTY(S.[OBJECT_ID],'IsUserTable') = 1
------------------Historical index Stats from Last restart of SQL Server
SELECT
t.name AS 'Table',
Count(i.user_seeks) as 'Indexes',
SUM(i.user_seeks + i.user_scans + i.user_lookups)
AS 'Total accesses',
SUM(i.user_seeks) AS 'Seeks',
SUM(i.user_scans) AS 'Scans',
SUM(i.user_lookups) AS 'Lookups',
SUM(i.user_updates) AS 'Updates'
FROM
sys.dm_db_index_usage_stats i RIGHT OUTER JOIN
sys.tables t ON (t.object_id = i.object_id)
GROUP BY
i.object_id,
t.name
ORDER BY [Total accesses] DESC
---------------------------------------------------------Optional MaxDop Setting Recommended:
select case
when cpu_count / hyperthread_ratio > 8 then 8
else cpu_count / hyperthread_ratio
end as optimal_maxdop_setting
from sys.dm_os_sys_info;
---------------------------------Defragment SQL Server Indexes:
Quick script to defragment SQL Server indexes
Here is a quick script that will defragment the indexes in your database and upd
ates the statistics. If the indexes are fragmented in more than one database the
n you should run this script on each one of your databases. Beware, don t run this
script while your database is in use because rebuilding your indexes will impac
t the response times of queries.

set nocount on
DECLARE @sql_string NVARCHAR(max)
DECLARE @table_Name sysname

DECLARE @Schema_Name sysname


DECLARE Table_Cur CURSOR FOR
SELECT t.Name, s.Name
FROM sys.tables t inner join sys.schemas s on t.Schema_id = s.Schema_Id
OPEN Table_Cur
FETCH NEXT FROM Table_Cur
INTO @table_Name, @Schema_Name
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql_string = 'ALTER INDEX ALL ON [' + @Schema_Name + '].[' + @table_Name +
'] REBUILD'
PRINT @sql_string
begin try
EXEC sp_ExecuteSQL @sql_string
end try
begin catch
select
ERROR_NUMBER() AS ErrorNumber
,ERROR_MESSAGE() AS ErrorMessage;
end catch
SET @sql_string = 'UPDATE STATISTICS [' + @Schema_Name + '].[' + @table_Name + '
]'
PRINT @sql_string
begin try
EXEC sp_ExecuteSQL @sql_string
end try
begin catch
select
ERROR_NUMBER() AS ErrorNumber
,ERROR_MESSAGE() AS ErrorMessage;
end catch
FETCH NEXT FROM Table_Cur
INTO @table_Name, @Schema_Name
END
CLOSE Table_Cur
DEALLOCATE Table_Cur

---------------------/*
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_

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
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

SET @command = @command + N PARTITION=


PRINT @Database;
PRINT
;
PRINT
;
PRINT @command;
PRINT
;
EXEC (@command);
PRINT N Executed: + @command;
END;

+ CAST(@partitionnum AS nvarchar(10));

Close and deallocate the cursor.


CLOSE partitions;
DEALLOCATE partitions;
Drop the temporary table.
DROP TABLE #work_to_do;
END ALTER REORGANIZE/REBUILD
UPDATE STATISTICS FOR EACH DATABASE ON ALL TABLES
PRINT @Database;
EXECUTE SP_UPDATESTATS;
FETCH NEXT FROM DatabaseCursor INTO @Database
END
CLOSE DatabaseCursor
DEALLOCATE DatabaseCursor
----------------------Single DB
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
rebuilding.
IF @frag < 30.0
SET @command = N'ALTER INDEX ' + @indexname + N' ON ' + @schemaname + N'.' + @o
bjectname + N' REORGANIZE';
IF @frag >= 30.0
SET @command = N'ALTER INDEX ' + @indexname + N' ON ' + @schemaname + N'.' + @o
bjectname + N' REBUILD';
IF @partitioncount > 1
SET @command = @command + N' PARTITION=' + CAST(@partitionnum AS nvarchar(10));
-- PRINT @Database;
PRINT ' ';
;
--PRINT
--PRINT @command;
-- PRINT
;
EXEC (@command);
PRINT N'Executed: ' + @command;
END;
-- Close and deallocate the cursor.
CLOSE partitions;
DEALLOCATE partitions;
-- Drop the temporary table.
DROP TABLE #work_to_do;
-END ALTER REORGANIZE/REBUILD
--UPDATE STATISTICS FOR EACH DATABASE ON ALL TABLES
--PRINT @Database;
EXECUTE SP_UPDATESTATS;
---------------------------------------------------------------------------------------------------------------------To turn on this feature across the board for all databases and all users you can
issue the following statement:
USE master
GO
GRANT VIEW ANY DEFINITION TO PUBLIC

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,

CAST(W1.pct AS DECIMAL(12, 2)) AS pct,


CAST(SUM(W2.pct) AS DECIMAL(12, 2)) AS running_pct
FROM Waits AS W1
INNER JOIN Waits AS W2
ON W2.rn <= W1.rn
GROUP BY W1.rn, W1.wait_type, W1.wait_time_s, W1.pct
HAVING SUM(W2.pct) - W1.pct < 99; -- percentage threshold
---------------------SELECT [name], [value], [value_in_use]
FROM [sys].[configurations]
WHERE [name] = 'max degree of parallelism'
----------------------------------Index Generation Scripts:
SELECT ' CREATE ' +
CASE WHEN I.is_unique = 1 THEN ' UNIQUE ' ELSE '' END

I.type_desc COLLATE DATABASE_DEFAULT +' INDEX ' +


I.name + ' ON '

Schema_name(T.Schema_id)+'.'+T.name + ' ( ' +


KeyColumns + ' ) ' +
ISNULL(' INCLUDE ('+IncludedColumns+' ) ','') +
ISNULL(' WHERE '+I.Filter_definition,'') + ' WITH ( ' +
CASE WHEN I.is_padded = 1 THEN ' PAD_INDEX = ON ' ELSE ' PAD_INDEX = OFF '
END + ',' +
'FILLFACTOR = '+CONVERT(CHAR(5),CASE WHEN I.Fill_factor = 0 THEN 100 ELSE I
.Fill_factor END) + ',' +
-- default value
'SORT_IN_TEMPDB = OFF ' + ','

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

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 = 1
WHERE IC1.object_id = IC2.object_id
AND IC1.index_id = IC2.index_id
GROUP BY IC1.object_id,C.name,index_id
FOR XML PATH('')), 1, 2, '') IncludedColumns
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) tmp1
WHERE IncludedColumns IS NOT NULL ) tmp2
ON tmp2.object_id = I.object_id AND tmp2.index_id = I.index_id
WHERE I.is_primary_key = 0 AND I.is_unique_constraint = 0
--AND I.Object_id = object_id('Person.Address') --Comment for all tables
--AND I.name = 'IX_Address_PostalCode' --comment for all indexes
---------------------------------------------------------------------------------Select

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 (NOLOCK)


A.[Object_ID] = C.object_id
And A.Index_ID = C.Index_ID
And C.is_included_column = 0
Order by C.key_Ordinal Asc
For XML Path('')
)
,1,1,'') + ') '
+ CASE WHEN A.type = 1 THEN ''
ELSE Coalesce('Include ('
+ Stuff(
(
Select
',' + QuoteName(COL_NAME
(A.[object_id],C.column_id))
From

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)

ELSE quotename(C.name) + '(' + F.Partition_Column +


')' END + ';' --if it uses partition scheme then need partition column
As nvarchar(Max)) As Index_Create_Statement
, C.name AS FileGroupName
, 'DROP INDEX ' + quotename(A.[Name]) + ' On ' + quotename(S.name) +
'.' + quotename(OBJECT_NAME(A.[object_id])) + ';' AS Index_Drop_Statement
From
SYS.Indexes A WITH (NOLOCK)
INNER JOIN
sys.objects B WITH (NOLOCK)
ON A.object_id = B.object_id
INNER JOIN
SYS.schemas S
ON B.schema_id = S.schema_id
INNER JOIN
SYS.data_spaces C WITH (NOLOCK)
ON A.data_space_id = C.data_space_id
INNER JOIN
SYS.stats D WITH (NOLOCK)
ON A.object_id = D.object_id
AND A.index_id = D.stats_id
Inner Join
--The below code is to find out what data compression type was used
by the index. If an index is not partitioned, it is easy as only one data compre
ssion
--type can be used. If the index is partitioned, then each partition
can be configued to use the different data compression. This is hard to general
ize,
--for simplicity, I just use the data compression type used most for
the index partitions for all partitions. You can later rebuild the index partit
ion to
--the appropriate data compression type you want to use
(
select object_id, index_id, Data_Compression, ROW_NUMBER() Over(
Partition By object_id, index_id Order by COUNT(*) Desc) As Main_Compression
From sys.partitions WITH (NOLOCK)
Group BY object_id, index_id, Data_Compression
) P
ON A.object_id = P.object_id
AND A.index_id = P.index_id
AND P.Main_Compression = 1
Outer APPLY
(
SELECT COL_NAME(A.object_id, E.column_id) AS Partition_Column
From
sys.index_columns E WITH (NOLOCK)
WHERE E.object_id = A.object_id
AND E.index_id = A.index_id
AND E.partition_ordinal = 1
) F
Where
A.type IN (1,2) --clustered and nonclustered
AND B.Type != 'S'
AND is_primary_key = 0 --this is not for primary key constraint
AND OBJECT_NAME(A.[object_id]) not like 'queue_messages_%'
AND OBJECT_NAME(A.[object_id]) not like 'filestream_tombstone_%'
AND OBJECT_NAME(A.[object_id]) not like 'sys%' --if you have index s
tart with sys then remove it
OPTION (Recompile);
--------------------------------------------------------------------------------------------------------------------------

--------------------------------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

FETCH NEXT FROM DatabaseCursor INTO @Database


END
CLOSE DatabaseCursor
DEALLOCATE DatabaseCursor

----------------------------------------------------------------------------------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

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

Script to check 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
ORDER BY indexstats.avg_fragmentation_in_percent DESC
================================================================================
============================================================
Script to Find Missing Indexes on a Database.
SELECT TOP 1000
dm_mid.database_id AS DatabaseID,
dm_migs.avg_user_impact*(dm_migs.user_seeks+dm_migs.user_scans) Avg_Estimated_Im
pact,
dm_migs.last_user_seek AS Last_User_Seek,
OBJECT_NAME(dm_mid.OBJECT_ID,dm_mid.database_id) AS [TableName],
'CREATE INDEX [IX_' + OBJECT_NAME(dm_mid.OBJECT_ID,dm_mid.database_id) + '_'
+ REPLACE(REPLACE(REPLACE(ISNULL(dm_mid.equality_columns,''),', ','_'),'[',''),'
]','') +
CASE
WHEN dm_mid.equality_columns IS NOT NULL AND dm_mid.inequality_columns IS NOT NU
LL THEN '_'
ELSE ''
END
+ REPLACE(REPLACE(REPLACE(ISNULL(dm_mid.inequality_columns,''),', ','_'),'[','')
,']','')
+ ']'
+ ' ON ' + dm_mid.statement
+ ' (' + ISNULL (dm_mid.equality_columns,'')
+ CASE WHEN dm_mid.equality_columns IS NOT NULL AND dm_mid.inequality_columns I
S NOT NULL THEN ',' ELSE
'' END
+ ISNULL (dm_mid.inequality_columns, '')
+ ')'
+ ISNULL (' INCLUDE (' + dm_mid.included_columns + ')', '') AS Create_Statement
FROM sys.dm_db_missing_index_groups dm_mig
INNER JOIN sys.dm_db_missing_index_group_stats dm_migs
ON dm_migs.group_handle = dm_mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details dm_mid
ON dm_mig.index_handle = dm_mid.index_handle
WHERE dm_mid.database_ID = DB_ID()
ORDER BY Avg_Estimated_Impact DESC
GO
--------------------------------Missing indexes: ( Clustered / non -CLustered)
SELECT sys.objects.name, (avg_total_user_cost * avg_user_impact) * (user_seeks
+ user_scans) AS Impact, 'CREATE NONCLUSTERED INDEX ix_IndexName ON ' + sys.obj
ects.name COLLATE DATABASE_DEFAULT + ' ( ' + IsNull(mid.equality_columns, '') +

CASE WHEN mid.inequality_columns IS NULL


THEN ''
ELSE CASE
WHEN mid.equality_columns IS NULL
THEN ''
ELSE ','
END + mid.inequality_columns END + ' ) ' + CASE WHEN mid.included_columns IS NUL
L
THEN ''
ELSE 'INCLUDE (' + mid.included_columns + ')' END
+ ';' AS CreateIndexStatement, mid.equality_columns, mid.inequality_columns, mi
d.included_columns
FROM sys.dm_db_missing_index_group_stats AS migs
INNER JOIN sys.dm_db_missing_index_groups AS mig ON migs.group_handle = mig.
index_group_handle
INNER JOIN sys.dm_db_missing_index_details AS mid
ON mig.index_handle = mid.index_handle AND mid.database_id = DB_ID()
INNER JOIN sys.objects WITH (nolock) ON mid.OBJECT_ID = sys.objects.OBJECT_ID
WHERE
(migs.group_handle IN
(
SELECT
TOP (500) group
_handle
FROM
sys.dm_db_missing_index_group_stats WITH (nolo
ck)
ORDER BY (avg_total_user_cost * avg_user_impact) * (user_seeks +
user_scans) DESC))
AND OBJECTPROPERTY(sys.objects.OBJECT_ID, 'isuserta
ble')=1
ORDER BY 2 DESC , 3 DESC
------------------------------------Restore Script from List of Backup files:
USE Master;
GO
SET NOCOUNT ON
-- 1 - Variable declaration
DECLARE @dbName sysname
DECLARE @backupPath NVARCHAR(500)
DECLARE @cmd NVARCHAR(500)
DECLARE @fileList TABLE (backupFile NVARCHAR(255))
DECLARE @lastFullBackup NVARCHAR(500)
DECLARE @lastDiffBackup NVARCHAR(500)
DECLARE @backupFile NVARCHAR(500)
-- 2 - Initialize variables
SET @dbName = 'Customer'
SET @backupPath = 'D:\SQLBackups\'
-- 3 - get list of files
SET @cmd = 'DIR /b ' + @backupPath
INSERT INTO @fileList(backupFile)
EXEC master.sys.xp_cmdshell @cmd
-- 4 - Find latest full backup
SELECT @lastFullBackup = MAX(backupFile)
FROM @fileList
WHERE backupFile LIKE '%.BAK'
AND backupFile LIKE @dbName + '%'
SET @cmd = 'RESTORE DATABASE ' + @dbName + ' FROM DISK = '''
+ @backupPath + @lastFullBackup + ''' WITH NORECOVERY, REPLACE'
PRINT @cmd
-- 4 - Find latest diff backup
SELECT @lastDiffBackup = MAX(backupFile)
FROM @fileList
WHERE backupFile LIKE '%.DIF'

AND backupFile LIKE @dbName + '%'


AND backupFile > @lastFullBackup
-- check to make sure there is a diff backup
IF @lastDiffBackup IS NOT NULL
BEGIN
SET @cmd = 'RESTORE DATABASE ' + @dbName + ' FROM DISK = '''
+ @backupPath + @lastDiffBackup + ''' WITH NORECOVERY'
PRINT @cmd
SET @lastFullBackup = @lastDiffBackup
END
-- 5 - check for log backups
DECLARE backupFiles CURSOR FOR
SELECT backupFile
FROM @fileList
WHERE backupFile LIKE '%.TRN'
AND backupFile LIKE @dbName + '%'
AND backupFile > @lastFullBackup
OPEN backupFiles
-- Loop through all the files for the database
FETCH NEXT FROM backupFiles INTO @backupFile
WHILE @@FETCH_STATUS = 0
BEGIN
SET @cmd = 'RESTORE LOG ' + @dbName + ' FROM DISK = '''
+ @backupPath + @backupFile + ''' WITH NORECOVERY'
PRINT @cmd
FETCH NEXT FROM backupFiles INTO @backupFile
END
CLOSE backupFiles
DEALLOCATE backupFiles
-- 6 - put database in a useable state
SET @cmd = 'RESTORE DATABASE ' + @dbName + ' WITH RECOVERY'
PRINT @cmd
---------------------------------------------------------------------------------------Auto generate SQL Server database restore scripts:

DECLARE
DECLARE
DECLARE
DECLARE

@databaseName sysname
@backupStartDate datetime
@backup_set_id_start INT
@backup_set_id_end INT

-- set database to be used


SET @databaseName = 'enterDatabaseNameHere'
SELECT @backup_set_id_start = MAX(backup_set_id)
FROM msdb.dbo.backupset
WHERE database_name = @databaseName AND type = 'D'

SELECT @backup_set_id_end = MIN(backup_set_id)


FROM msdb.dbo.backupset
WHERE database_name = @databaseName AND type = 'D'
AND backup_set_id > @backup_set_id_start
IF @backup_set_id_end IS NULL SET @backup_set_id_end = 999999999
SELECT backup_set_id, 'RESTORE DATABASE ' + @databaseName + ' FROM DISK = '''
+ mf.physical_device_name + ''' WITH NORECOVERY'
FROM
msdb.dbo.backupset b,
msdb.dbo.backupmediafamily mf
WHERE
b.media_set_id = mf.media_set_id
AND b.database_name = @databaseName
AND b.backup_set_id = @backup_set_id_start
UNION
SELECT backup_set_id, 'RESTORE LOG ' + @databaseName + ' FROM DISK = '''
+ mf.physical_device_name + ''' WITH NORECOVERY'
FROM
msdb.dbo.backupset b,
msdb.dbo.backupmediafamily mf
WHERE
b.media_set_id = mf.media_set_id
AND b.database_name = @databaseName
AND b.backup_set_id >= @backup_set_id_start AND b.backup_set_id < @bac
kup_set_id_end
AND b.type = 'L'
UNION
SELECT 999999999 AS backup_set_id, 'RESTORE DATABASE ' + @databaseName + ' WITH
RECOVERY'
ORDER BY backup_set_id
-------------------------------------------------------------------------------------------------------------------------------------

You might also like