Monday, September 21, 2015

Reverse Engineers Database Mail Settings.

http://www.sqlservercentral.com/Forums/Topic982618-391-1.aspx



USE msdb
GO

Declare @TheResults varchar(max),
        @vbCrLf CHAR(2)
SET @vbCrLf = CHAR(13) + CHAR(10)        
SET @TheResults = '
use master
go
sp_configure ''show advanced options'',1
go
reconfigure with override
go
sp_configure ''Database Mail XPs'',1
--go
--sp_configure ''SQL Mail XPs'',0
go
reconfigure
go
'
SELECT @TheResults = @TheResults  + '
--#################################################################################################
-- BEGIN Mail Settings ' + p.name + '
--#################################################################################################
IF NOT EXISTS(SELECT * FROM msdb.dbo.sysmail_profile WHERE  name = ''' + p.name + ''') 
  BEGIN
    --CREATE Profile [' + p.name + ']
    EXECUTE msdb.dbo.sysmail_add_profile_sp
      @profile_name = ''' + p.name + ''',
      @description  = ''' + ISNULL(p.description,'') + ''';
  END --IF EXISTS profile
  '
  +
  '
  IF NOT EXISTS(SELECT * FROM msdb.dbo.sysmail_account WHERE  name = ''' + a.name + ''')
  BEGIN
    --CREATE Account [' + a.name + ']
    EXECUTE msdb.dbo.sysmail_add_account_sp
    @account_name            = ' + CASE WHEN a.name                IS NULL THEN ' NULL ' ELSE + '''' + a.name                  + '''' END + ',
    @email_address           = ' + CASE WHEN a.email_address       IS NULL THEN ' NULL ' ELSE + '''' + a.email_address         + '''' END + ',
    @display_name            = ' + CASE WHEN a.display_name        IS NULL THEN ' NULL ' ELSE + '''' + a.display_name          + '''' END + ',
    @replyto_address         = ' + CASE WHEN a.replyto_address     IS NULL THEN ' NULL ' ELSE + '''' + a.replyto_address       + '''' END + ',
    @description             = ' + CASE WHEN a.description         IS NULL THEN ' NULL ' ELSE + '''' + a.description           + '''' END + ',
    @mailserver_name         = ' + CASE WHEN s.servername          IS NULL THEN ' NULL ' ELSE + '''' + s.servername            + '''' END + ',
    @mailserver_type         = ' + CASE WHEN s.servertype          IS NULL THEN ' NULL ' ELSE + '''' + s.servertype            + '''' END + ',
    @port                    = ' + CASE WHEN s.port                IS NULL THEN ' NULL ' ELSE + '''' + CONVERT(VARCHAR,s.port) + '''' END + ',
    @username                = ' + CASE WHEN c.credential_identity IS NULL THEN ' NULL ' ELSE + '''' + c.credential_identity   + '''' END + ',
    @password                = ' + CASE WHEN c.credential_identity IS NULL THEN ' NULL ' ELSE + '''NotTheRealPassword''' END + ', 
    @use_default_credentials = ' + CASE WHEN s.use_default_credentials = 1 THEN ' 1 ' ELSE ' 0 ' END + ',
    @enable_ssl              = ' + CASE WHEN s.enable_ssl = 1              THEN ' 1 ' ELSE ' 0 ' END + ';
  END --IF EXISTS  account
  '
  + '
IF NOT EXISTS(SELECT *
              FROM msdb.dbo.sysmail_profileaccount pa
                INNER JOIN msdb.dbo.sysmail_profile p ON pa.profile_id = p.profile_id
                INNER JOIN msdb.dbo.sysmail_account a ON pa.account_id = a.account_id  
              WHERE p.name = ''' + p.name + '''
                AND a.name = ''' + a.name + ''') 
  BEGIN
    -- Associate Account [' + a.name + '] to Profile [' + p.name + ']
    EXECUTE msdb.dbo.sysmail_add_profileaccount_sp
      @profile_name = ''' + p.name + ''',
      @account_name = ''' + a.name + ''',
      @sequence_number = ' + CONVERT(VARCHAR,pa.sequence_number) + ' ;
  END --IF EXISTS associate accounts to profiles
--#################################################################################################
-- Drop Settings For ' + p.name + '
--#################################################################################################
/*
IF EXISTS(SELECT *
            FROM msdb.dbo.sysmail_profileaccount pa
              INNER JOIN msdb.dbo.sysmail_profile p ON pa.profile_id = p.profile_id
              INNER JOIN msdb.dbo.sysmail_account a ON pa.account_id = a.account_id  
            WHERE p.name = ''' + p.name + '''
              AND a.name = ''' + a.name + ''')
  BEGIN
    EXECUTE msdb.dbo.sysmail_delete_profileaccount_sp @profile_name = ''' + p.name + ''',@account_name = ''' + a.name + '''
  END 
IF EXISTS(SELECT * FROM msdb.dbo.sysmail_account WHERE  name = ''' + a.name + ''')
  BEGIN
    EXECUTE msdb.dbo.sysmail_delete_account_sp @account_name = ''' + a.name + '''
  END
IF EXISTS(SELECT * FROM msdb.dbo.sysmail_profile WHERE  name = ''' + p.name + ''') 
  BEGIN
    EXECUTE msdb.dbo.sysmail_delete_profile_sp @profile_name = ''' + p.name + '''
  END
*/
  ' 
FROM msdb.dbo.sysmail_profile p
INNER JOIN msdb.dbo.sysmail_profileaccount pa ON  p.profile_id = pa.profile_id
INNER JOIN msdb.dbo.sysmail_account a         ON pa.account_id = a.account_id 
LEFT OUTER JOIN msdb.dbo.sysmail_server s     ON a.account_id = s.account_id
LEFT OUTER JOIN sys.credentials c    ON s.credential_id = c.credential_id

   ;WITH E01(N) AS (SELECT 1 UNION ALL SELECT 1 UNION ALL  
                    SELECT 1 UNION ALL SELECT 1 UNION ALL  
                    SELECT 1 UNION ALL SELECT 1 UNION ALL  
                    SELECT 1 UNION ALL SELECT 1 UNION ALL  
                    SELECT 1 UNION ALL SELECT 1), --         10 or 10E01 rows  
         E02(N) AS (SELECT 1 FROM E01 a, E01 b),  --        100 or 10E02 rows  
         E04(N) AS (SELECT 1 FROM E02 a, E02 b),  --     10,000 or 10E04 rows  
         E08(N) AS (SELECT 1 FROM E04 a, E04 b),  --100,000,000 or 10E08 rows  
         --E16(N) AS (SELECT 1 FROM E08 a, E08 b),  --10E16 or more rows than you'll EVER need,  
         Tally(N) AS (SELECT ROW_NUMBER() OVER (ORDER BY N) FROM E08),  
       ItemSplit(  
                 ItemOrder,  
                 Item  
                ) as (  
                      SELECT N,  
                        SUBSTRING(@vbCrLf + @TheResults + @vbCrLf,N + DATALENGTH(@vbCrLf),CHARINDEX(@vbCrLf,@vbCrLf + @TheResults + @vbCrLf,N + DATALENGTH(@vbCrLf)) - N - DATALENGTH(@vbCrLf))  
                      FROM Tally  
                      WHERE N < DATALENGTH(@vbCrLf + @TheResults)  
                      --WHERE N < DATALENGTH(@vbCrLf + @INPUT) -- REMOVED added @vbCrLf  
                        AND SUBSTRING(@vbCrLf + @TheResults + @vbCrLf,N,DATALENGTH(@vbCrLf)) = @vbCrLf --Notice how we find the delimiter  
                     )  
  select  
    row_number() over (order by ItemOrder) as ItemID,  
    Item  
  from ItemSplit  
 
  

Monday, August 17, 2015

Check for AutoGrow

http://blogs.msdn.com/b/blogdoezequiel/archive/2010/11/16/the-sql-swiss-army-knife-5-checking-autogrow-times.aspx#.VdIE1_lViko


DECLARE @curr_tracefilename VARCHAR(500), @indx int, @base_tracefilename VARCHAR(500);
SELECT @curr_tracefilename = path FROM sys.traces WHERE is_default = 1;
SET @curr_tracefilename = REVERSE(@curr_tracefilename);
SELECT @indx = PATINDEX('%\%', @curr_tracefilename) ;
SET @curr_tracefilename = REVERSE(@curr_tracefilename) ;
SET @base_tracefilename = LEFT( @curr_tracefilename,LEN(@curr_tracefilename) - @indx) + '\log.trc' ;
WITH AutoGrow_CTE (databaseid, filename, Growth, Duration, StartTime, EndTime)
AS
(
SELECT databaseid, filename, SUM(IntegerData*8) AS Growth, Duration, StartTime, EndTime--, CASE WHEN EventClass =
FROM ::fn_trace_gettable(@base_tracefilename, default)
WHERE EventClass >= 92 AND EventClass <= 95
AND DATEDIFF(hh,StartTime,GETDATE()) < 24 -- Last 24h
GROUP BY databaseid, filename, IntegerData, Duration, StartTime, EndTime
)
SELECT DB_NAME(database_id) AS DatabaseName,
mf.name AS LogicalName,
mf.size*8 AS CurrentSize_KB,
mf.type_desc AS 'File_Type',
CASE WHEN is_percent_growth = 1 THEN 'Percentage' ELSE 'Pages' END AS 'Growth_Type',
ag.Growth AS Growth_KB,
Duration/1000 AS Duration_ms,
ag.StartTime,
ag.EndTime
FROM sys.master_files mf
LEFT OUTER JOIN AutoGrow_CTE ag
ON mf.database_id=ag.databaseid
AND mf.name=ag.filename
WHERE ag.Growth > 0 --Only where growth occurred
GROUP BY database_id, mf.name, mf.size, ag.Growth, ag.Duration, ag.StartTime, ag.EndTime, is_percent_growth, mf.growth, mf.type_desc
ORDER BY DatabaseName, LogicalName, ag.StartTime

Friday, July 24, 2015

Sp_changearticle schema_option




declare @schema_option varbinary(8) = 0x0000000008000001  --< PUT YOUR SCHEMA_OPTION HERE

set nocount on
declare @OptionTable table ( HexValue varbinary(8), IntValue as cast(HexValue as bigint), OptionDescription varchar(255))
insert into @OptionTable (HexValue, OptionDescription)
select 0x01 ,'Generates object creation script'
union all  select 0x02 ,'Generates procs that propogate changes for the article'
union all  select 0x04 ,'Identity columns are scripted using the IDENTITY property'
union all  select 0x08 ,'Replicate timestamp columns (if not set timestamps are replicated as binary)'
union all  select 0x10 ,'Generates corresponding clustered index'
union all  select 0x20 ,'Converts UDT to base data types'
union all  select 0x40 ,'Create corresponding nonclustered indexes'
union all  select 0x80 ,'Replicate pk constraints'
union all  select 0x100 ,'Replicates user triggers'
union all  select 0x200 ,'Replicates foreign key constraints'
union all  select 0x400 ,'Replicates check constraints'
union all  select 0x800  ,'Replicates defaults'
union all  select 0x1000 ,'Replicates column-level collation'
union all  select 0x2000 ,'Replicates extended properties'
union all  select 0x4000 ,'Replicates UNIQUE constraints'
union all  select 0x8000 ,'Not valid'
union all  select 0x10000 ,'Replicates CHECK constraints as NOT FOR REPLICATION so are not enforced during sync'
union all  select 0x20000 ,'Replicates FOREIGN KEY constraints as NOT FOR REPLICATION so are not enforced during sync'
union all  select 0x40000 ,'Replicates filegroups'
union all  select 0x80000 ,'Replicates partition scheme for partitioned table'
union all  select 0x100000 ,'Replicates partition scheme for partitioned index'
union all  select 0x200000 ,'Replicates table statistics'
union all  select 0x400000 ,'Default bindings'
union all  select 0x800000 ,'Rule bindings'
union all  select 0x1000000 ,'Full text index'
union all  select 0x2000000 ,'XML schema collections bound to xml columns not replicated'
union all  select 0x4000000 ,'Replicates indexes on xml columns'
union all  select 0x8000000 ,'Creates schemas not present on subscriber'
union all  select 0x10000000 ,'Converts xml columns to ntext'
union all  select 0x20000000 ,'Converts (max) data types to text/image'
union all  select 0x40000000 ,'Replicates permissions'
union all  select 0x80000000 ,'Drop dependencies to objects not part of publication'
union all  select 0x100000000 ,'Replicate FILESTREAM attribute (2008 only)'
union all  select 0x200000000 ,'Converts date & time data types to earlier versions'
union all  select 0x400000000 ,'Replicates compression option for data & indexes'
union all  select 0x800000000  ,'Store FILESTREAM data on its own filegroup at subscriber'
union all  select 0x1000000000 ,'Converts CLR UDTs larger than 8000 bytes to varbinary(max)'
union all  select 0x2000000000 ,'Converts hierarchyid to varbinary(max)'
union all  select 0x4000000000 ,'Replicates filtered indexes'
union all  select 0x8000000000 ,'Converts geography, geometry to varbinary(max)'
union all  select 0x10000000000 ,'Replicates geography, geometry indexes'
union all  select 0x20000000000 ,'Replicates SPARSE attribute '
                 
select HexValue,OptionDescription as 'Schema Options Enabled'
From @OptionTable where (cast(@schema_option as bigint) & cast(HexValue as bigint)) <> 0


select cast(
 cast(0x01 AS BIGINT) --DEFAULT Generates object creation script
| cast(0x02 AS BIGINT) --DEFAULT Generates procs that propogate changes for the article
| cast(0x04 AS BIGINT) --Identity columns are scripted using the IDENTITY property
| cast(0x08 AS BIGINT) --DEFAULT Replicate timestamp columns (if not set timestamps are replicated as binary)
| cast(0x10 AS BIGINT) --DEFAULT Generates corresponding clustered index
--| cast(0x20 AS BIGINT) --Converts UDT to base data types
--| cast(0x40 AS BIGINT) --Create corresponding nonclustered indexes
| cast(0x80 AS BIGINT) --DEFAULT Replicate pk constraints
--| cast(0x100 AS BIGINT) --Replicates user triggers
--| cast(0x200 AS BIGINT) --Replicates foreign key constraints
--| cast(0x400 AS BIGINT) --Replicates check constraints
--| cast(0x800 AS BIGINT)  --Replicates defaults
| cast(0x1000 AS BIGINT) --DEFAULT Replicates column-level collation
--| cast(0x2000 AS BIGINT) --Replicates extended properties
| cast(0x4000 AS BIGINT) --DEFAULT Replicates UNIQUE constraints
--| cast(0x8000 AS BIGINT) --Not valid
| cast(0x10000 AS BIGINT) --DEFAULT Replicates CHECK constraints as NOT FOR REPLICATION so are not enforced during sync
| cast(0x20000 AS BIGINT) --DEFAULT Replicates FOREIGN KEY constraints as NOT FOR REPLICATION so are not enforced during sync
--| cast(0x40000 AS BIGINT) --Replicates filegroups (filegroups must already exist on subscriber)
--| cast(0x80000 AS BIGINT) --Replicates partition scheme for partitioned table
--| cast(0x100000 AS BIGINT) --Replicates partition scheme for partitioned index
--| cast(0x200000 AS BIGINT) --Replicates table statistics
--| cast(0x400000 AS BIGINT) --Default bindings
--| cast(0x800000 AS BIGINT) --Rule bindings
--| cast(0x1000000 AS BIGINT) --Full text index
--| cast(0x2000000 AS BIGINT) --XML schema collections bound to xml columns not replicated
--| cast(0x4000000 AS BIGINT) --Replicates indexes on xml columns
| cast(0x8000000 AS BIGINT) --DEFAULT Creates schemas not present on subscriber
--| cast(0x10000000 AS BIGINT) --Converts xml columns to ntext
--| cast(0x20000000 AS BIGINT) --Converts (max) data types to text/image
--| cast(0x40000000 AS BIGINT) --Replicates permissions
--| cast(0x80000000 AS BIGINT) --Drop dependencies to objects not part of publication
--| cast(0x100000000 AS BIGINT) --Replicate FILESTREAM attribute (2008 only)
--| cast(0x200000000 AS BIGINT) --Converts date & time data types to earlier versions
| cast(0x400000000 AS BIGINT) --Replicates compression option for data & indexes
--| cast(0x800000000 AS BIGINT)  --Store FILESTREAM data on its own filegroup at subscriber
--| cast(0x1000000000 AS BIGINT) --Converts CLR UDTs larger than 8000 bytes to varbinary(max)
--| cast(0x2000000000 AS BIGINT) --Converts hierarchyid to varbinary(max)
--| cast(0x4000000000 AS BIGINT) --Replicates filtered indexes
--| cast(0x8000000000 AS BIGINT) --Converts geography, geometry to varbinary(max)
--| cast(0x10000000000 AS BIGINT) --Replicates geography, geometry indexes
--| cast(0x20000000000 AS BIGINT) --Replicates SPARSE attribute

AS BINARY(8)) as Schema_Option 

Thursday, July 23, 2015

IndexUsageAnalysis

USE [SysAdmin]
GO

/****** Object:  Table [dbo].[DATAUSAGEANALYSIS]    Script Date: 1/28/2015 5:14:29 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[DATAUSAGEANALYSIS](
[db_name] [nvarchar](128) NULL,
[schema_name] [nvarchar](128) NULL,
[table_name] [nvarchar](128) NULL,
[index_name] [sysname] NULL,
[type] [varchar](4) NULL,
[is_unique] [bit] NULL,
[cnstr] [varchar](2) NULL,
[key_columns] [nvarchar](max) NULL,
[included_columns] [nvarchar](max) NULL,
[location] [sysname] NOT NULL,
[rows] [bigint] NULL,
[pages] [bigint] NULL,
[MB] [decimal](9, 2) NULL,
[user_seeks] [bigint] NULL,
[user_scans] [bigint] NULL,
[user_lookups] [bigint] NULL,
[user_updates] [bigint] NULL,
[Statistics_last_collected] [datetime] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO



EXEC master..sp_MSForeachdb '
USE [?]
IF ''?'' <> ''master'' AND ''?'' <> ''model'' AND ''?'' <> ''msdb'' AND ''?'' <> ''tempdb''
BEGIN
INSERT INTO SYSADMIN..DATAUSAGEANALYSIS
exec [?]..sp_indexinfo @missing_ix = 0
END
'




select * from SYSADMIN..DATAUSAGEANALYSIS

Wednesday, July 22, 2015

RML Read Trace Summary



use sqlnexus
go
SELECT ub.OrigText AS OrigQuery,
ub.NormText AS NormQuery
,bh1.HashID
, bh1.AvgDuration_MS
, bh1.AvgCPU_MS
, bh1.AvgReads
, bh1.AvgWrites
, bh1.Calls
, bh1.SumCPU
, bh1.SumDuration
, bh1.SumReads
, bh1.SumWrites

  ,  100. * SUM(calls) / SUM(SUM(calls)) OVER() AS PctofTotalCalls,
ROW_NUMBER() OVER(ORDER BY SUM(calls) DESC) AS TotalCalls_rank


 ,  100. * SUM(calls*AvgDuration_MS) / SUM(SUM(calls*AvgDuration_MS)) OVER() AS PctofTotalDur,
  ROW_NUMBER() OVER(ORDER BY SUM(calls*AvgDuration_MS) DESC) AS TotalDuration_rank
 
  ,  100. * SUM(calls*avgreads) / SUM(SUM(calls*avgreads)) OVER() AS PctofTotalReads,
  ROW_NUMBER() OVER(ORDER BY SUM(calls*avgreads) DESC) AS TotalReads_rank
 
,  100. * SUM(calls*AvgWrites) / SUM(SUM(calls*AvgWrites)) OVER() AS PctofTotalWrites,
  ROW_NUMBER() OVER(ORDER BY SUM(calls*AvgWrites) DESC) AS TotalWrites_rank
 
  ,  100. * SUM(calls*AvgCPU_MS) / SUM(SUM(calls*AvgCPU_MS)) OVER() AS PctofTotalCpu,
  ROW_NUMBER() OVER(ORDER BY SUM(calls*AvgCPU_MS) DESC) AS TotalCPU_rank

--into SqlNexus_Awe0227

FROM (
SELECT ub.HashID, AVG(b.Duration)/1000.00 AS AvgDuration_MS, AVG(b.Reads) AS AvgReads, AVG(b.Writes) AS AvgWrites, AVG(b.CPU) AS AvgCPU_MS, COUNT(1) AS Calls, Sum(b.Duration) AS SumDuration, sum(b.Reads) AS SumReads, Sum(b.Writes) AS SumWrites, Sum(b.CPU) AS SumCPU
FROM ReadTrace.tblUniqueBatches AS ub
INNER JOIN ReadTrace.tblBatches AS b
ON ub.HashID = b.HashID
--where DBID in (599)
GROUP BY ub.HashID
) AS bh1
INNER JOIN ReadTrace.tblUniqueBatches AS ub
ON bh1.HashID = ub.HashID
group by ub.OrigText
,ub.NormText
,bh1.HashID
, bh1.AvgDuration_MS
,bh1.AvgCPU_MS
, bh1.AvgReads
, bh1.AvgWrites
, bh1.Calls
, bh1.SumCPU
, bh1.SumDuration
, bh1.SumReads
, bh1.SumWrites

order by SumDuration desc

Thursday, June 25, 2015

Query Stats Ranking





use master



Select
SQL as SqlStatement
,DBNAME
,OBJECTNAME

,100. * SUM(total_execution_time_ms) / SUM(SUM(total_execution_time_ms)) OVER() AS PCTOFTOTAL_TOTAL_EXECUTION_TIME_MS
,ROW_NUMBER() OVER(ORDER BY SUM(total_execution_time_ms) DESC) AS TOTAL_EXECUTION_TIME_MS_RANK

,100. * SUM(total_cpu_time_ms) / SUM(SUM(total_cpu_time_ms)) OVER() AS PCTOFTOTAL_TOTAL_CPU_TIME_MS_MS
,ROW_NUMBER() OVER(ORDER BY SUM(total_cpu_time_ms) DESC) AS TOTAL_CPU_TIME_MS_RANK

,100. * SUM(total_logical_reads) / SUM(SUM(total_logical_reads)) OVER() AS PCTOFTOTAL_TOTAL_LOGICAL_READS
,ROW_NUMBER() OVER(ORDER BY SUM(total_logical_reads) DESC) AS TOTAL_LOGICAL_READS_RANK

,100. * SUM(total_logical_reads) / SUM(SUM(total_logical_reads)) OVER() AS PCTOFTOTAL_TOTAL_LOGICAL_READS
,ROW_NUMBER() OVER(ORDER BY SUM(total_logical_reads) DESC) AS TOTAL_LOGICAL_READS_RANK

,100. * SUM(total_logical_writes) / SUM(SUM(total_logical_writes)) OVER() AS PCTOFTOTAL_TOTAL_LOGICAL_WRITES
,ROW_NUMBER() OVER(ORDER BY SUM(total_logical_writes) DESC) AS TOTAL_LOGICAL_WRITES_RANK

,cast(100.00 * SUM(execution_count) / SUM(SUM(execution_count)) OVER() as numeric(32,2) ) AS PctofTotalExecution_count
,ROW_NUMBER() OVER(ORDER BY SUM(execution_count) DESC) AS Execution_Count_Rank

,total_execution_time_ms
,total_cpu_time_ms
,total_logical_reads
,total_logical_writes
,execution_count
,query_hash
,query_plan_hash
,cast(query_plan as XML) as queryplan
from (

SELECT TOP 200
        SUBSTRING(text, statement_start_offset/2 + 1,
             (CASE WHEN statement_end_offset = -1
                             THEN LEN(CONVERT(nvarchar(max), text)) * 2
                             ELSE statement_end_offset
                END - statement_start_offset)/2) as SQL              
        ,coalesce( db_name(query_text.DBID) , DB_Name(F_DB.DatabaseID) ) as DBNAME
        , Object_name(query_text.objectid,query_text.DBID) as OBJECTNAME
   ,s.total_worker_time / 1000 AS total_cpu_time_ms
      ,s.total_elapsed_time / 1000 AS total_execution_time_ms
,s.total_logical_reads
,s.total_logical_writes

,s.execution_count as execution_count
,s.query_hash
,s.query_plan_hash
,c.query_plan
,((s.total_elapsed_time)/ s.execution_count)/ 1000 AS avg_execution_time_ms
,  ((s.total_worker_time * 1.00)/ s.execution_count)/ 1000 AS avg_cpu_time_ms
,  ((s.total_logical_reads * 1.00)/ s.execution_count) AS avg_logical_reads
,  ((s.total_logical_writes * 1.00)/ s.execution_count) AS avg_logical_writes
FROM sys.dm_exec_query_stats s
  CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS query_text
      cross apply sys.dm_exec_text_query_plan(plan_handle, statement_start_offset, statement_end_offset) c
       CROSS APPLY (SELECT CONVERT(int, value) AS [DatabaseID]
              FROM sys.dm_exec_plan_attributes(s.plan_handle)
              WHERE attribute = N'dbid') AS F_DB
--ORDER BY total_worker_time DESC
ORDER BY total_elapsed_time DESC
--ORDER BY total_logical_reads DESC


 ) as a
Group BY SQL,DBNAME,OBJECTNAME, total_cpu_time_ms, total_execution_time_ms, total_logical_reads, total_logical_writes, execution_count,query_hash,query_plan_hash
,query_plan

Order by
--a.total_cpu_time_ms desc
a.total_execution_time_ms desc
--a.total_logical_reads desc

Wednesday, June 3, 2015

Retreiving Sql Server 2012 Product Key from the registry


https://xzwang.wordpress.com/2013/06/22/retreiving-sql-server-2012-product-key-from-the-registry/


function Get-SQLserverKey {
## function to retrieve the license key of a SQL 2012 Server.
## by Jakob Bindslet (jakob@bindslet.dk)
## 2012 Modification by Xian Wang (daanno2@gmail.com)
param ($targets = ".")
$hklm = 2147483650
$regPath = "SOFTWARE\Microsoft\Microsoft SQL Server\110\Tools\Setup"
$regValue1 = "DigitalProductId"
$regValue2 = "PatchLevel"
$regValue3 = "Edition"
Foreach ($target in $targets) {
$productKey = $null
$win32os = $null
$wmi = [WMIClass]"\\$target\root\default:stdRegProv"
$data = $wmi.GetBinaryValue($hklm,$regPath,$regValue1)
[string]$SQLver = $wmi.GetstringValue($hklm,$regPath,$regValue2).svalue
[string]$SQLedition = $wmi.GetstringValue($hklm,$regPath,$regValue3).svalue
$binArray = ($data.uValue)[0..16]
$charsArray = "B","C","D","F","G","H","J","K","M","P","Q","R","T","V","W","X","Y","2","3","4","6","7","8","9"
## decrypt base24 encoded binary data
For ($i = 24; $i -ge 0; $i--) {
$k = 0
For ($j = 14; $j -ge 0; $j--) {
$k = $k * 256 -bxor $binArray[$j]
$binArray[$j] = [math]::truncate($k / 24)
$k = $k % 24
}
$productKey = $charsArray[$k] + $productKey
If (($i % 5 -eq 0) -and ($i -ne 0)) {
$productKey = "-" + $productKey
}
}
$win32os = Get-WmiObject Win32_OperatingSystem -computer $target
$obj = New-Object Object
$obj | Add-Member Noteproperty Computer -value $target
$obj | Add-Member Noteproperty OSCaption -value $win32os.Caption
$obj | Add-Member Noteproperty OSArch -value $win32os.OSArchitecture
$obj | Add-Member Noteproperty SQLver -value $SQLver
$obj | Add-Member Noteproperty SQLedition -value $SQLedition
$obj | Add-Member Noteproperty ProductKey -value $productkey
$obj
}
}