Showing posts with label Optimization. Show all posts
Showing posts with label Optimization. Show all posts

Thursday, August 2, 2012

Database Restore History

USE msdb;
GO
Select top 20
DBRestored= destination_database_name,
SourceFile= physical_name,
RestoreDate= restore_date
from RestoreHistory h
inner join BackupSet b
on h.backup_set_id = b.backup_set_id
inner join BackupFile f
on f.backup_set_id = b.backup_set_id
order by RestoreDate desc
GO

MvM

Monday, July 23, 2012

[Microsoft][ODBC SQL Server Driver][SQL Server]DBCC failed because the following SET options have incorrect settings: ‘QUOTED_IDENTIFIER’.

I have seen this error lot of times in SQL Server 2000 Maintenance Plans. When job fails, it doesn’t specifically say anything in the ‘Job History’. So, what I used to do is to run the Optimisation code (copied from the job) in Query Analyzer. This will list out each step result for the plan. Thats how I used to see this error message. This specifically appears for the ‘Integrity Checks’ and ‘Optimisation’ Job Plans.

Here’s how to resolve it.

Optimizations Job for DB Maintenance Plan ‘DB Maintenance Plan name‘For example, add the parameters to the command as shown in the following command:
EXECUTE master.dbo.xp_sqlmaint N’-S ServerName\InstanceName -PlanID -WriteHistory -RebldIdx 10 -SupportComputedColumn’

Integrity Checks Job for DB Maintenance Plan ‘DB Maintenance Plan name‘For example, add the parameters to the command as shown in the following command:
EXECUTE master.dbo.xp_sqlmaint N’-S ServerName\InstanceName -PlanID -WriteHistory -CkDB -SupportComputedColumn’

More details and explanations can be found in http://support.microsoft.com/kb/902388

MvM

Thursday, July 12, 2012

Change Maintenance Plan Owner to ‘sa’


I always had this annoying issue where in I had to update the job owner to ‘sa’ once someone had modified a maintenance plan. This happens when a user logs in with his id (which usually everyone does) and modifies a Maintenance Plan and then saves it. This automatically changes the owner of the job corresponding to it.
Below mentioned query is handy when you need to update lot of Maintenance Plans like this.
–SQL 2005
UPDATE msdb.dbo.sysdtspackages90
SET ownersid =SUSER_SID(‘sa’)
WHERE name = ‘MAINT’
 –SQL 2008
UPDATE msdb.dbo.sysssispackages
SET ownersid =SUSER_SID(‘sa’)
WHERE name = ‘MAINT’
–**************************
MvM

Database, Users and their DB Roles (SQL Server 2000 & 2005)


SQL SERVER 2005
DECLARE @db_name SYSNAME, @sql VARCHAR(1000)
DECLARE db_cursor CURSOR FOR
SELECT Name FROM sys.databases
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @db_name
WHILE (@@FETCH_STATUS= 0)
BEGIN
SET @sql =‘SELECT ”’+ @db_name + ”’ AS [Database],
USER_NAME(role_principal_id) AS [Role], USER_NAME(member_principal_id) AS [User]
FROM ‘+ @db_name +‘.sys.database_role_members’
EXEC(@sql)
 FETCH NEXT FROM db_cursor INTO @db_name
END
CLOSE db_cursor
DEALLOCATE db_cursor
SQL SERVER 2000
DECLARE @db_name SYSNAME, @sql VARCHAR(1000)
 DECLARE db_cursor CURSOR FOR
SELECT Name FROM master..sysdatabases
 OPEN db_cursor FETCH NEXT
FROM db_cursor INTO @db_name
WHILE (@@FETCH_STATUS= 0)
 BEGIN
SET @sql =‘SELECT ”’+ @db_name + ”’ AS [Database],
USER_NAME(memberuid) AS [Role], USER_NAME(groupuid) AS [User] 
FROM sysmembers’
EXEC (@sql)
FETCH NEXT FROM db_cursor INTO @db_name
END
CLOSE db_cursor
DEALLOCATE db_cursor;
–====================================
MvM

Query to find Users and their Database Roles in SQL Server 2000


SELECT USER_NAME(memberuid) as UserName,
USER_NAME(groupuid) as Role
FROM sysmembers ;
MvM

Query to find Server Roles and its members in SQL Server 2000


select ‘ServerRole’= spv.name, ‘MemberName’= lgn.name
from master.dbo.spt_values spv,
master.dbo.sysxlogins lgn
where spv.low = 0 and spv.type=‘SRV’
and lgn.srvid IS NULL and spv.number & lgn.xstatus = spv.number;
MvM

Friday, July 6, 2012

Stored Procedure to list Users & their Database Roles


USE [msdb]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[List_DBRoles]')
AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[List_DBRoles]
GO

CREATE procedure [dbo].[List_DBRoles]
( @database nvarchar(128)=null, @user varchar(20)=null,
@dbo char(1)=null, @access char(1)=null,
@security char(1)=null, @ddl char(1)=null,
@datareader char(1)=null, @datawriter char(1)=null,
@denyread char(1)=null, @denywrite char(1)=null
) as

declare @dbname varchar(200)
declare @mSql1 varchar(8000)

CREATE TABLE #DBROLES
(DBName sysname not null, UserName sysname not null,
db_owner varchar(3) not null, db_accessadmin varchar(3) not null,
db_securityadmin varchar(3) not null, db_ddladmin varchar(3) not null,
db_datareader varchar(3) not null, db_datawriter varchar(3) not null,
db_denydatareader varchar(3) not null, db_denydatawriter varchar(3) not null
)

DECLARE DBName_Cursor CURSOR FOR
select name
from master.dbo.sysdatabases 
where name not in ('mssecurity','tempdb')
order by name

OPEN DBName_Cursor
FETCH NEXT FROM DBName_Cursor INTO @dbname
WHILE @@FETCH_STATUS = 0
BEGIN

Set @mSQL1 = ' Insert into #DBROLES ( DBName, UserName, db_owner, db_accessadmin,
db_securityadmin, db_ddladmin, db_datareader, db_datawriter, db_denydatareader, db_denydatawriter )
SELECT  '+''''+@dbName +''''+ ' as DBName ,UserName, '+char(13)+'
Max(CASE RoleName WHEN ''db_owner'' THEN ''Yes'' ELSE ''No'' END) AS db_owner,
Max(CASE RoleName WHEN ''db_accessadmin '' THEN ''Yes'' ELSE ''No'' END) AS db_accessadmin ,
Max(CASE RoleName WHEN ''db_securityadmin'' THEN ''Yes'' ELSE ''No'' END) AS db_securityadmin,
Max(CASE RoleName WHEN ''db_ddladmin'' THEN ''Yes'' ELSE ''No'' END) AS db_ddladmin,
Max(CASE RoleName WHEN ''db_datareader'' THEN ''Yes'' ELSE ''No'' END) AS db_datareader,
Max(CASE RoleName WHEN ''db_datawriter'' THEN ''Yes'' ELSE ''No'' END) AS db_datawriter,
Max(CASE RoleName WHEN ''db_denydatareader'' THEN ''Yes'' ELSE ''No'' END) AS db_denydatareader,
Max(CASE RoleName WHEN ''db_denydatawriter'' THEN ''Yes'' ELSE ''No'' END) AS db_denydatawriter
from (
select b.name as USERName, c.name as RoleName
from [' + @dbName+'].dbo.sysmembers a '+char(13)+
'join ['+ @dbName+'].dbo.sysusers b '+char(13)+
'on a.memberuid = b.uid join ['+@dbName +'].dbo.sysusers c
on a.groupuid = c.uid )s
Group by USERName
order by UserName'

Execute (@mSql1)

FETCH NEXT FROM DBName_Cursor INTO @dbname
END
CLOSE DBName_Cursor
DEALLOCATE DBName_Cursor

Select * from #DBRoles
where ((@database is null) OR (DBName LIKE '%'+@database+'%')) AND
((@user is null) OR (UserName LIKE '%'+@user+'%')) AND
((@dbo is null) OR (db_owner = 'Yes')) AND
((@access is null) OR (db_accessadmin = 'Yes')) AND
((@security is null) OR (db_securityadmin = 'Yes')) AND
((@ddl is null) OR (db_ddladmin = 'Yes')) AND
((@datareader is null) OR (db_datareader = 'Yes')) AND
((@datawriter is null) OR (db_datawriter = 'Yes')) AND
((@denyread is null) OR (db_denydatareader = 'Yes')) AND
((@denywrite is null) OR (db_denydatawriter = 'Yes'))

drop table #DBRoles
------
MvM

Query to find Database Roles & its associated members

USE master
DECLARE @name VARCHAR(50) -- database name 
CREATE TABLE #temprr(RoleName nvarchar(max),MemberName nvarchar(max), LoginType nvarchar(max))
DECLARE db_cursor CURSOR FOR
SELECT name FROM sys.databases
OPEN db_cursor 
FETCH NEXT FROM db_cursor INTO @name 
WHILE @@FETCH_STATUS= 0 
BEGIN
PRINT @name
INSERT INTO #temprr
EXEC('USE ['+ @name +']; 
select rp.name as RoleName, mp.name as MemberName, mp.type_desc as Type from sys.database_role_members drm join sys.database_principals rp on (drm.role_principal_id = rp.principal_id) join sys.database_principals mp on (drm.member_principal_id = mp.principal_id)')
FETCH NEXT FROM db_cursor INTO @name 
END
CLOSE db_cursor 
DEALLOCATE db_cursor
SELECT * FROM #temprr
where MemberName notlike'NT%'and MemberName notlike'##%'
order by MemberName
drop table #temprr;
MvM

Identifying SQL Server logins with overlapping Server Roles

Here’s the query to find it…


SELECT SPMember.[login name], SPRole.name AS 'role name'
FROM master.sys.server_principals SPRole 
INNER JOIN master.sys.server_role_members SRM 
ON SPRole.principal_id = SRM.role_principal_id 
INNER JOIN ( SELECT SP.name AS 'login name', SP.principal_id 
FROM master.sys.server_principals sp_roles 
INNER JOIN master.sys.server_role_members SRM ON sp_roles.principal_id = SRM.role_principal_id
INNER JOIN master.sys.server_principals SP ON SRM.member_principal_id = SP.principal_id 
WHERE sp_roles.type_desc ='SERVER_ROLE'
GROUP BY SP.name, SP.principal_id 
HAVING COUNT(SP.name)> 1) AS SPMember 
ON SRM.member_principal_id = SPMember.principal_id 
ORDER BY SPMember.[login name] 
MvM

Audit users, logins, roles & permissions (Server & Database Level) in SQL Server 2005 & 2008.

I have been looking around to audit some SQL DBs which I have in 2005 & 2008. I wanted to see the permissions set at the DB level as well as server level. Below are the queries.
Script to find server level logins and roles assigned
SELECT a.name as LoginName,a.type_desc AS LoginType, a.default_database_name AS DefaultDBName,
CASE WHEN b.sysadmin = 1 THEN 'sysadmin'
WHEN b.securityadmin=1 THEN 'securityadmin'
WHEN b.serveradmin=1 THEN 'serveradmin'
WHEN b.setupadmin=1 THEN 'setupadmin'
WHEN b.processadmin=1 THEN 'processadmin'
WHEN b.diskadmin=1 THEN 'diskadmin'
WHEN b.dbcreator=1 THEN 'dbcreator'
WHEN b.bulkadmin=1 THEN 'bulkadmin'
ELSE 'Public' END AS 'ServerRole'
FROM sys.server_principals a JOIN master..syslogins b ON a.sid=b.sid
WHERE a.type <> 'R' AND a.name NOT LIKE '##%'
Script to find database users and roles assigned
DECLARE @DBuser_sql VARCHAR(4000)
DECLARE @DBuser_table TABLE (DBName VARCHAR(200), UserName VARCHAR(250), LoginType VARCHAR(500), AssociatedRole VARCHAR(200))
SET @DBuser_sql='SELECT ''?'' AS DBName,a.name AS Name,a.type_desc AS LoginType,USER_NAME(b.role_principal_id) AS AssociatedRole
FROM [?].sys.database_principals a 
LEFT OUTER JOIN [?].sys.database_role_members b 
ON a.principal_id=b.member_principal_id 
WHERE a.sid NOT IN (0x01,0x00) AND a.sid IS NOT NULL 
AND a.type NOT IN (''C'') AND a.is_fixed_role <> 1 
AND a.name NOT LIKE ''##%'' AND ''[?]'' 
NOT IN (''master'',''msdb'',''model'',''tempdb'') 
ORDER BY Name' INSERT @DBuser_table 
EXEC sp_MSforeachdb @command1=@dbuser_sql
SELECT *FROM @DBuser_table ORDERBY DBName
Script to find Object level permission for user databases
DECLARE @Obj_sql VARCHAR(2000)
DECLARE @Obj_table TABLE (DBName VARCHAR(200), UserName VARCHAR(250), ObjectName VARCHAR(500), Permission VARCHAR(200))
SET @Obj_sql='select ''?'' as DBName,U.name as username, O.name as object, permission_name as permission from [?].sys.database_permissions  join [?].sys.sysusers U on grantee_principal_id = uid join [?].sys.sysobjects O on major_id = id  WHERE ''[?]'' NOT IN (''master'',''msdb'',''model'',''tempdb'') order by U.name '
INSERT @Obj_table 
EXEC sp_msforeachdb @command1=@Obj_sql 
SELECT * FROM @Obj_table

MvM

Cannot resolve collation conflict for column 1 in SELECT statement

“Cannot resolve collation conflict for column 1 in SELECT statement.”
I got this error when I was trying to run a script. This is basically because the column collation has been set at a different level than the server.
eg: SELECT FirstName +' '+LastName FROM dbo.Students
This could be rectified by specifying the column collation along with the Select statement.
eg: SELECT FirstName +' '+ LastName 
COLLATE SQL_Latin1_General_CP1_CI_AI LastName 
FROM dbo.Students
MvM

Missing Indexes, Plans & Plan cache.

Below listed are some of t he common queries I use to find missing indexes, costly queries running per day, plans that use a specific index and objects in plan cache.
I normally dont just go and create the missing indexes suggested; I would rather look into the costly queries running per day and how many times are they run and then compare that list with the missing indexes one. Good thing about SQL Server 2008 is that it shows the missing index details and the query to create it in the costly queries list. Please use them wisely as indexes are damn costly !
FIND MISSING INDEXES
SELECT [statement] AS full_object_name,
unique_compiles, avg_user_impact, user_seeks, column_name, column_usage
FROM sys.dm_db_missing_index_groups G
JOIN sys.dm_db_missing_index_group_stats GS 
ON G.index_group_handle = GS.group_handle
JOIN sys.dm_db_missing_index_details D ON G.index_handle = D.index_handle
CROSS APPLY sys.dm_db_missing_index_columns(D.index_handle) DC 
ORDER BY avg_user_impact DESC;
TOP 25 COSTLY QUERIES FROM YESTERDAY
SELECT TOP 25 qs.execution_count,qs.last_execution_time, 
tot_CPU_inSec = qs.total_worker_time/1000000, 
avg_CPU_inSec =(qs.total_worker_time/1000000)/ qs.execution_count, 
tot_elapsed_time_inSec = 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
WHERE ((qs.total_worker_time/1000000)/ qs.execution_count)> 0 
and qs.last_execution_time >GETDATE()-1
ORDER BY ((qs.total_worker_time/1000000)/ qs.execution_count) DESC;
Plans that use an index
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
DECLARE @IndexName ASNVARCHAR(128)='ix2_spt_values_nu_nc';
-- Make sure the name passed is appropriately quoted
IF (LEFT(@IndexName, 1)<>'['AND RIGHT(@IndexName, 1)<>']') SET @IndexName =QUOTENAME(@IndexName);
--Handle the case where the left or right was quoted manually but not the opposite side
IF LEFT(@IndexName, 1)<>'['SET @IndexName ='['+@IndexName;
IF RIGHT(@IndexName, 1)<>']'SET @IndexName = @IndexName +']' ;
 -- Dig into the plan cache and find all plans using this index
;WITH XMLNAMESPACES
(DEFAULT'http://schemas.microsoft.com/sqlserver/2004/07/showplan')
SELECT stmt.value('(@StatementText)[1]','varchar(max)')AS SQL_Text,
obj.value('(@Database)[1]','varchar(128)') AS DatabaseName,
obj.value('(@Schema)[1]','varchar(128)') AS SchemaName,
obj.value('(@Table)[1]','varchar(128)') AS TableName,
obj.value('(@Index)[1]','varchar(128)') AS IndexName,
obj.value('(@IndexKind)[1]','varchar(128)') AS IndexKind, 
cp.plan_handle,query_plan
FROM sys.dm_exec_cached_plansAS cp
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp
CROSS APPLY query_plan.nodes('/ShowPlanXML/BatchSequence/Batch/Statements/StmtSimple')AS batch(stmt)
CROSS APPLY stmt.nodes('.//IndexScan/Object[@Index=sql:variable("@IndexName")]')AS idx(obj)
OPTION (MAXDOP 1,RECOMPILE);
List objects in Plan Cache
select count(*) as cached_pages_count,
       obj.name as objectname,
       ind.name as indexname,
       obj.index_id as indexid
from sys.dm_os_buffer_descriptors as bd
    inner join
    ( select object_id as objectid, object_name(object_id) as name,
       index_id, allocation_unit_id
       from sys.allocation_units as au
       inner join sys.partitions as p
       on au.container_id = p.hobt_id
       and (au.type = 1 or au.type = 3)
       union all
        select object_id as objectid, object_name(object_id) as name,
        index_id,allocation_unit_id
        from sys.allocation_units as au
            inner join sys.partitions as p
            on au.container_id = p.partition_id
            and au.type = 2
    ) as obj
       on bd.allocation_unit_id = obj.allocation_unit_id
left outer join sys.indexes ind 
  on  obj.objectid = ind.object_id
 and  obj.index_id = ind.index_id
where bd.database_id = db_id()
  and bd.page_type in ('data_page', 'index_page')
group by obj.name, ind.name, obj.index_id
order by cached_pages_count desc;
MvM