Thursday, August 16, 2018

Some useful SQL Queries


Block queries


SELECT
    spid
    ,sp.status
    ,loginame   = SUBSTRING(loginame, 1, 12)
    ,hostname   = SUBSTRING(hostname, 1, 12)
    ,blk        = CONVERT(char(3), blocked)
    ,open_tran
    ,dbname     = SUBSTRING(DB_NAME(sp.dbid),1,10)
    ,cmd
    ,waittype
    ,waittime
    ,last_batch
    ,SQLStatement       =
        SUBSTRING
        (
            qt.text,
            er.statement_start_offset/2,
            (CASE WHEN er.statement_end_offset = -1
                THEN LEN(CONVERT(nvarchar(MAX), qt.text)) * 2
                ELSE er.statement_end_offset
                END - er.statement_start_offset)/2
        )
FROM master.dbo.sysprocesses sp
LEFT JOIN sys.dm_exec_requests er
    ON er.session_id = sp.spid
OUTER APPLY sys.dm_exec_sql_text(er.sql_handle) as qt
WHERE spid IN (SELECT blocked FROM master.dbo.sysprocesses)
AND blocked = 0


      

Kill process  - kill and processID

kill 201;


check Index

select the db and run

SELECT ps.database_id, object_name(ps.OBJECT_ID) as table_name, ps.index_id, b.name as index_name, ps.avg_fragmentation_in_percent,ps.page_count
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS ps
INNER JOIN sys.indexes AS b ON ps.OBJECT_ID = b.OBJECT_ID
inner join sys.tables as c ON b.object_id = c.object_id
AND ps.index_id = b.index_id
WHERE ps.database_id = DB_ID()
and b.name is not null
ORDER BY ps.avg_fragmentation_in_percent desc



Check last executed stats


/* 1.Query to check when statistics was last executed */
SELECT
  st.object_id                          AS [Table ID]
, OBJECT_NAME(st.object_id)             AS [Table Name]
, st.name                               AS [Index Name]
, STATS_DATE(st.object_id, st.stats_id) AS [LastUpdated]
, modification_counter                  AS [Rows Modified]
FROM
sys.stats st
CROSS APPLY
sys.dm_db_stats_properties(st.object_id, st.stats_id) AS sp
WHERE
STATS_DATE(st.object_id, st.stats_id)<=DATEADD(DAY,-1,GETDATE()) 
AND modification_counter > 0
AND OBJECTPROPERTY(st.object_id,'IsUserTable')=1
order by OBJECT_NAME(st.object_id)





read sp


sp_helptext 'myDb.spName'



few




SELECT
       r.session_id
       ,st.TEXT AS batch_text
       ,SUBSTRING(st.TEXT, statement_start_offset / 2 + 1, (
                     (
                           CASE
                                  WHEN r.statement_end_offset = - 1
                                         THEN (LEN(CONVERT(NVARCHAR(max), st.TEXT)) * 2)
                                  ELSE r.statement_end_offset
                                  END
                           ) - r.statement_start_offset
                     ) / 2 + 1) AS statement_text
       ,qp.query_plan AS 'XML Plan'
       ,r.*
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) AS st
CROSS APPLY sys.dm_exec_query_plan(r.plan_handle) AS qp
ORDER BY cpu_time DESC





select
    P.spid,
       P.status
,   right(convert(varchar,
            dateadd(ms, datediff(ms, P.last_batch, getdate()), '1900-01-01'),
            121), 12) as 'batch_duration'
,   P.program_name
,   P.hostname
,   P.loginame
from master.dbo.sysprocesses P
where P.spid > 50
and      P.status not in ('background', 'sleeping','runnable')
and      P.cmd not in ('AWAITING COMMAND'
                    ,'MIRROR HANDLER'
                    ,'LAZY WRITER'
                    ,'CHECKPOINT SLEEP'
                    ,'RA MANAGER')
order by batch_duration desc





Disable and enable windows taskschedular

move "C:\Windows\System32\Tasks\Test\TestPS" "C:\Windows\System32\Tasks\Test\TestPS.bak"


-- enable

move "C:\Windows\System32\Tasks\Test\TestPS.bak" "C:\Windows\System32\Tasks\Test\TestPS" 

powershell script to get some performance stats

#////////////////////////////////////////////////////////////////////////////////////////////


Param($globalSelectedItems)

foreach ($globalSelectedItem in $globalSelectedItems) {

$selectedObject = $globalSelectedItem["DisplayName"]
$hostpath = $globalSelectedItem["Path"]      #Get the server name
}

$class = get-scomclass -Name Microsoft.Windows.Server.OperatingSystem

#Look for OS instance of server
$selectedserverOS = Get-SCOMClassInstance -class $class | ? {$_.Path -ilike $hostpath}

$dataObject = $ScriptContext.CreateInstance("xsd://OSMEMPROC!val/stat")

$dataObject["Id"] = "ItemSelected"
$dataObject["Path"] = $hostpath

$aggregationInterval = 60

#Last 60 minutes (1hr)
  $dt = New-TimeSpan -minute $aggregationInterval   
  $now = Get-Date 
  $from = $now.Subtract($dt)

#Note: the GetMonitoringPerformanceData retrieves data recorded in UTC. So you may need to add some extra lines in the script to handle that as some local times may be a future date and no data will be returned.

$perfRules = $selectedserverOS.GetMonitoringPerformanceData()

foreach ($perfRule in $perfRules)
{
#Get % Processor Time Stat
if($perfRule.CounterName  -eq "% Processor Time")  {
      $data = $perfRule.GetValues($from, $now) | % { $_.SampleValue } | Measure-Object –Average 
 
     $CPUStat =  [math]::round($data.Average,2)
     $dataObject["CPUStat"] = $CPUStat
  }
#Get % Memory Used Stat
  if($perfRule.CounterName  -eq "PercentMemoryUsed")  {
      $data = $perfRule.GetValues($from, $now) | % { $_.SampleValue } | Measure-Object –Average 

     $MemState = [math]::round($data.Average,2)
     $dataObject["MemStat"] =  $MemState
  }
}

$ScriptContext.ReturnCollection.Add($dataObject)

#////////////////////////////////////////////////////////////////////////////////////////////


Powershell script to send mail


$a = ""

$table1 = Get-Childitem D:\MyFiles | where {$_.LastwriteTime -le (Get-date).AddDays(-7)}|where {$_.Name -like "myFile.xls" }| Select Name,LastWriteTime |ConvertTo-Html -head $a -Property Name,LastWriteTime


$FromEmail="sender@test.com"
$ToEmail="receiver@test.com"
$CcEmail="cc1@test.com;cc2@test.com;cc3@test.com"
$SMTPMail="mailserver.test.com"


 Function sendEmail([string]$emailFrom, [string]$emailTo,[string]$emailCc, [string]$subject,[string]$body,[string]$smtpServer)
{
$email = New-Object System.Net.Mail.MailMessage 
$email.From = $emailFrom
$email.To.Add($emailTo)
$email.Cc.Add($CcEmail)
$email.Subject = $subject
$email.IsBodyHTML = $true
$email.Body = $body
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($email)
}
$date=get-date
$message = "Hi Team,
"
$message += "
"
$message += "Test File file has not been uploaded today
"
$message += "
$table1
"
$message += "Thanks
Test Team
"


sendEmail -emailFrom $fromEmail -emailTo $ToEmail -emailCc $CcEmail -subject "Test file Status -$($date)" -body $message -smtpServer $SMTPMail

Few useful powershell scripts I have worked with

Some useful powershell scripts
--------------------------------

Check file created before date range
-------------------------------------

$lastWrite = (get-item "D:\MYdirectory\myExcel.xls").LastWriteTime
$timespan = new-timespan -days 7 -hours 0 -minutes 0

if (((get-date) - $lastWrite) -gt $timespan)
{
   Write-Host "old";
} else
{
   Write-Host "new";
}





Send mails
-----------


$lastModifiedDate = (Get-Item "D:\Revenue_FTP_Files\FTP_Bottom_Up_Revenue.xls").LastWriteTime;
Write-Host $lastModifiedDate;

$table1 = Get-Childitem D:\Revenue_FTP_Files | where {$_.LastwriteTime -le (Get-date).AddDays(-7)}|where {$_.Name -like "FTP_Bottom_Up_Revenue.xls" }| Select Name,LastWriteTime |ConvertTo-Html -head $a -Property Name,LastWriteTime
Write-Host $table1;


### get details
$Today = Get-Date
$FileDate = (Get-ChildItem "D:\Revenue_FTP_Files\FTP_Bottom_Up_Revenue.xls").LastWriteTime
if ($FileDate -ge $Today){"ok"} else {"not ok"}

Write-Host $Today;
Write-Host $FileDate;

$day = (get-date 10/04/2017).DayOfWeek
Write-Host $day;
$lastWriteshort = (get-item "D:\Revenue_FTP_Files\FTP_Bottom_Up_Revenue.xls").LastWriteTime.ToShortDateString();
Write-Host $lastWriteshort;
Write-Host "------------";
$dateValue = (get-date).ToShortDateString();
Write-Host $dateValue;

if (((get-date) - $lastWrite) -gt $timespan)
{
   Write-Host "old";
} else
{
   Write-Host "new";
}

$lastWrite = (get-item "D:\MyDirectory\myFile.xls").LastWriteTime
$tuesdayTimespan = new-timespan -days 2 -hours 0 -minutes 0
$wednesdayTimespan = new-timespan -days 1 -hours 12 -minutes 0
$thursdayTimespan = new-timespan -days 2 -hours 0 -minutes 0
$fridayTimespan = new-timespan -days 3 -hours 0 -minutes 0
$saturdayTimespan = new-timespan -days 4 -hours 0 -minutes 0
$sundayTimespan = new-timespan -days 6 -hours 0 -minutes 0
$mondayTimespan = new-timespan -days 6 -hours 0 -minutes 0



$day = (get-date).DayOfWeek

if($day -eq "Tuesday" ){
if ((get-date).ToShortDateString() -ne $lastWrite.ToShortDateString())
{
   Write-Host "sending mail";
   sendEmail -emailFrom $fromEmail -emailTo $ToEmail -emailCc $CcEmail -subject "My file file Status -$($date)" -body $message -smtpServer $SMTPMail
}
}
if($day -eq "Wednesday" ){
if (((get-date) - $lastWrite) -ge $wednesdayTimespan)
{
   Write-Host "sending mail.";
   sendEmail -emailFrom $fromEmail -emailTo $ToEmail -emailCc $CcEmail -subject "My file file Status -$($date)" -body $message -smtpServer $SMTPMail
}
}
if($day -eq "Thursday" ){
if (((get-date) - $lastWrite) -ge $thursdayTimespan)
{
   Write-Host "sending mail.";
   sendEmail -emailFrom $fromEmail -emailTo $ToEmail -emailCc $CcEmail -subject "My file file Status -$($date)" -body $message -smtpServer $SMTPMail
}

}
if($day -eq "Friday" ){
if (((get-date) - $lastWrite) -ge $fridayTimespan)
{
   Write-Host "sending mail.";
   sendEmail -emailFrom $fromEmail -emailTo $ToEmail -emailCc $CcEmail -subject "My file file Status -$($date)" -body $message -smtpServer $SMTPMail
}
}
if($day -eq "Saturday" ){
if (((get-date) - $lastWrite) -ge $saturdayTimespan)
{
   Write-Host "sending mail.";
   sendEmail -emailFrom $fromEmail -emailTo $ToEmail -emailCc $CcEmail -subject "My file file Status -$($date)" -body $message -smtpServer $SMTPMail
}
}
if($day -eq "Sunday" ){
if (((get-date) - $lastWrite) -ge $sundayTimespan)
{
   Write-Host "sending mail.";
   sendEmail -emailFrom $fromEmail -emailTo $ToEmail -emailCc $CcEmail -subject "My file file Status -$($date)" -body $message -smtpServer $SMTPMail
}
}
if($day -eq "Monday" ){
if (((get-date) - $lastWrite) -ge $mondayTimespan)
{
   Write-Host "sending mail.";
   sendEmail -emailFrom $fromEmail -emailTo $ToEmail -emailCc $CcEmail -subject "My file file Status -$($date)" -body $message -smtpServer $SMTPMail
}
}






Server Availability
--------------------


 
#### Spreadsheet Location
 $DirectoryToSaveTo = "C:\project\"
 $date=Get-Date -format "yyyy-MM-d"
 $Filename="serverinfo-$($date)"
 $FromEmail="
 $ToEmail="
 $SMTPMail="
 
 ###InputLocation
 $Computers = Get-Content "C:\project\servers.txt"
 
 
# before we do anything else, are we likely to be able to save the file?
# if the directory doesn't exist, then create it
if (!(Test-Path -path "$DirectoryToSaveTo")) #create it if not existing
  {
  New-Item "$DirectoryToSaveTo" -type directory | out-null
  }
 


#Create a new Excel object using COM 
$Excel = New-Object -ComObject Excel.Application
$Excel.visible = $True
$Excel = $Excel.Workbooks.Add()
$Sheet = $Excel.Worksheets.Item(1)

$sheet.Name = 'Server Inventory'
#Create a Title for the first worksheet
$row = 1
$Column = 1
$Sheet.Cells.Item($row,$column)= 'Server Inventory'

$range = $Sheet.Range("a1","s2")
$range.Merge() | Out-Null
$range.VerticalAlignment = -4160

#Give it a nice Style so it stands out
$range.Style = 'Title'

#Increment row for next set of data
$row++;$row++

#Save the initial row so it can be used later to create a border
#Counter variable for rows
$intRow = $row
$xlOpenXMLWorkbook=[int]51

#Read thru the contents of the SQL_Servers.txt file

$Sheet.Cells.Item($intRow,1)  ="Name"
$Sheet.Cells.Item($intRow,2)  ="status"
$Sheet.Cells.Item($intRow,3)  ="OS"
$Sheet.Cells.Item($intRow,4)  ="Domain Role"
$Sheet.Cells.Item($intRow,5)  ="ProcessorName"
$Sheet.Cells.Item($intRow,6)  ="Manufacturer"
$Sheet.Cells.Item($intRow,7)  ="Model"
$Sheet.Cells.Item($intRow,8)  ="SystemType"
$Sheet.Cells.Item($intRow,9)  ="Last Boot Time"
$Sheet.Cells.Item($intRow,10) ="Bios Version"
$Sheet.Cells.Item($intRow,11) ="CPU Info"
$Sheet.Cells.Item($intRow,12) ="NoOfProcessors"
$Sheet.Cells.Item($intRow,13) ="Total Physical Memory"
$Sheet.Cells.Item($intRow,14) ="Total Free Physical Memory"
$Sheet.Cells.Item($intRow,15) ="Total Virtual Memory"
$Sheet.Cells.Item($intRow,16) ="Total Free Virtual Memory"
$Sheet.Cells.Item($intRow,17) ="Disk Info"
$Sheet.Cells.Item($intRow,18) ="FQDN"
$Sheet.Cells.Item($intRow,19) ="IPAddress"

for ($col = 1; $col –le 19; $col++)
     {
          $Sheet.Cells.Item($intRow,$col).Font.Bold = $True
          $Sheet.Cells.Item($intRow,$col).Interior.ColorIndex = 48
          $Sheet.Cells.Item($intRow,$col).Font.ColorIndex = 34
     }

$intRow++


Function GetStatusCode

    Param([int] $StatusCode) 
    switch($StatusCode)
    {
        0         {"Success"}
        11001   {"Buffer Too Small"}
        11002   {"Destination Net Unreachable"}
        11003   {"Destination Host Unreachable"}
        11004   {"Destination Protocol Unreachable"}
        11005   {"Destination Port Unreachable"}
        11006   {"No Resources"}
        11007   {"Bad Option"}
        11008   {"Hardware Error"}
        11009   {"Packet Too Big"}
        11010   {"Request Timed Out"}
        11011   {"Bad Request"}
        11012   {"Bad Route"}
        11013   {"TimeToLive Expired Transit"}
        11014   {"TimeToLive Expired Reassembly"}
        11015   {"Parameter Problem"}
        11016   {"Source Quench"}
        11017   {"Option Too Big"}
        11018   {"Bad Destination"}
        11032   {"Negotiating IPSEC"}
        11050   {"General Failure"}
        default {"Failed"}
    }
}


Function GetUpTime
{
    param([string] $LastBootTime)
    $Uptime = (Get-Date) - [System.Management.ManagementDateTimeconverter]::ToDateTime($LastBootTime)
    "Days: $($Uptime.Days); Hours: $($Uptime.Hours); Minutes: $($Uptime.Minutes); Seconds: $($Uptime.Seconds)" 
}

   
   



foreach ($Computer in $Computers)
 {

 TRY {
 $OS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $Computer
 $Bios = Get-WmiObject -Class Win32_BIOS -ComputerName $Computer
 $sheetS = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $Computer
 $sheetPU = Get-WmiObject -Class Win32_Processor -ComputerName $Computer
 $drives = Get-WmiObject -ComputerName $Computer Win32_LogicalDisk | Where-Object {$_.DriveType -eq 3}
 $pingStatus = Get-WmiObject -Query "Select * from win32_PingStatus where Address='$Computer'"
 $IPAddress=(Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $Computer | ? {$_.IPEnabled}).ipaddress
 $FQDN=[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Name
 $OSRunning = $OS.caption + " " + $OS.OSArchitecture + " SP " + $OS.ServicePackMajorVersion
 $NoOfProcessors=$sheetS.numberofProcessors
 $name=$SheetPU|select name -First 1
 $Manufacturer=$sheetS.Manufacturer
 $Model=$sheetS.Model
 $systemType=$sheetS.SystemType
 $ProcessorName=$SheetPU|select name -First 1
 $DomainRole = $sheetS.DomainRole
 $TotalAvailMemory = $OS.totalvisiblememorysize/1kb
 $TotalVirtualMemory = $OS.totalvirtualmemorysize/1kb
 $TotalFreeMemory = $OS.FreePhysicalMemory/1kb
 $TotalFreeVirtualMemory = $OS.FreeVirtualMemory/1kb
 $TotalMem = "{0:N2}" -f $TotalAvailMemory
 $TotalVirt = "{0:N2}" -f $TotalVirtualMemory
 $FreeMem = "{0:N2}" -f $TotalFreeMemory
 $FreeVirtMem = "{0:N2}" -f $TotalFreeVirtualMemory
 $date = Get-Date
 $uptime = $OS.ConvertToDateTime($OS.lastbootuptime)
 $BiosVersion = $Bios.Manufacturer + " " + $Bios.SMBIOSBIOSVERSION + " " + $Bios.ConvertToDateTime($Bios.Releasedate)
 $sheetPUInfo = $name.Name + " & has " + $sheetPU.NumberOfCores + " Cores & the FSB is " + $sheetPU.ExtClock + " Mhz"
 $sheetPULOAD = $sheetPU.LoadPercentage
 
 if($pingStatus.StatusCode -eq 0)
    {
        $Status = GetStatusCode( $pingStatus.StatusCode )
    }
else
    {
    $Status = GetStatusCode( $pingStatus.StatusCode )
       }
   
   
 if (($DomainRole -eq "0") -or ($DomainRole -eq "1"))
 {
 $Role = "Work Station"
 }
 elseif (($DomainRole -eq "2") -or ($DomainRole -eq "3"))
 {
 $Role = "Member Server"
 }
 elseif (($DomainRole -eq "4") -or ($DomainRole -eq "5"))
 {
 $Role = "Domain Controller"
 }
 else
 {
 $Role = "Unknown"
 }
 }
 CATCH
 {
 $pcnotfound = "true"
 }
 #### Pump Data to Excel
 if ($pcnotfound -eq "true")
 {
 $sheet.Cells.Item($intRow, 1) = "$($computer) Not Found "
 }
 else
 {
 $sheet.Cells.Item($intRow, 1) = $computer
 $sheet.Cells.Item($intRow, 2) = $status
 $sheet.Cells.Item($intRow, 3) = $OSRunning
 $sheet.Cells.Item($intRow, 4) = $Role
 $sheet.Cells.Item($intRow, 5) = $name.name
 $Sheet.Cells.Item($intRow, 6) = $Manufacturer
 $Sheet.Cells.Item($intRow, 7) = $Model
 $Sheet.Cells.Item($intRow, 8) = $SystemType
 $sheet.Cells.Item($intRow, 9) = $uptime
 $sheet.Cells.Item($intRow, 10)= $BiosVersion
 $sheet.Cells.Item($intRow, 11)= $sheetPUInfo
 $sheet.Cells.Item($intRow, 12)=$NoOfProcessors
 $sheet.Cells.Item($intRow, 13)= "$TotalMem MB"
 $sheet.Cells.Item($intRow, 14)= "$FreeMem MB"
 $sheet.Cells.Item($intRow, 15)= "$TotalVirt MB"
 $sheet.Cells.Item($intRow, 16)= "$FreeVirtMem MB"
 $sheet.Cells.Item($intRow, 19)=$IPAddress
 $sheet.Cells.Item($intRow, 18)=$FQDN

 
$driveStr = ""
 foreach($drive in $drives)
 {
 $size1 = $drive.size / 1GB
 $size = "{0:N2}" -f $size1
 $free1 = $drive.freespace / 1GB
 $free = "{0:N2}" -f $free1
 $freea = $free1 / $size1 * 100
 $freeb = "{0:N2}" -f $freea
 $ID = $drive.DeviceID
 $driveStr += "$ID = Total Space: $size GB / Free Space: $free GB / Free (Percent): $freeb % ` "
 }
 $sheet.Cells.Item($intRow, 17) = $driveStr
 }

 
$intRow = $intRow + 1
 $pcnotfound = "false"
 }

$erroractionpreference = “SilentlyContinue” 

$Sheet.UsedRange.EntireColumn.AutoFit()



$filename = "$DirectoryToSaveTo$filename.xlsx"
if (test-path $filename ) { rm $filename } #delete the file if it already exists
$Sheet.UsedRange.EntireColumn.AutoFit()
$Excel.SaveAs($filename, $xlOpenXMLWorkbook) #save as an XML Workbook (xslx)
$Excel.Saved = $True
$Excel.Close()
$Excel.DisplayAlerts = $False
$Excel.quit()


Function sendEmail([string]$emailFrom, [string]$emailTo, [string]$subject,[string]$body,[string]$smtpServer,[string]$filePath)
{
#initate message
$email = New-Object System.Net.Mail.MailMessage 
$email.From = $emailFrom
$email.To.Add($emailTo)
$email.Subject = $subject
$email.Body = $body
# initiate email attachment 
$emailAttach = New-Object System.Net.Mail.Attachment $filePath
$email.Attachments.Add($emailAttach) 
#initiate sending email 
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($email)
}

#Call Function 

$message = @" 
Hi Team,

The Discovery of Windows Server and Disk Space information for all the listed instances.

Autogenerated Email!!! Please do not reply.

Thank you, 
xyz.com

"@       
$date=get-date

sendEmail -emailFrom $fromEmail -emailTo $ToEmail -subject "Windows Server Inventory & Disk Details -$($date)" -body $message -smtpServer $SMTPMail -filePath $filename




Create Check sum
-----------------

If the content is a string:

$someString = "Hello World!"
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$utf8 = new-object -TypeName System.Text.UTF8Encoding
$hash = [System.BitConverter]::ToString($md5.ComputeHash($utf8.GetBytes($someString)))
If the content is a file:

$someFilePath = "C:\foo.txt"
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($someFilePath)))


Security Issues : oracle tns listener remote poisoning

oracle tns listener remote poisoning

Solution
----------

E:\Oracle\product\11.2.0\client_1\NETWORK\ADMIN

File name = listener.ora

"DYNAMIC_REGISTRATION_LISTENER=OFF
dynamic_registration = off"

Some useful SQL Queries

Some Useful SQL commands
-------------------------

-- get database names
SELECT name,* FROM master.dbo.sysdatabases



Job History
-----------


USE msdb ; 
GO 

SELECT j.name JobName,h.step_name StepName,
CONVERT(CHAR(10), CAST(STR(h.run_date,8, 0) AS dateTIME), 111) RunDate,
STUFF(STUFF(RIGHT('000000' + CAST ( h.run_time AS VARCHAR(6 ) ) ,6),5,0,':'),3,0,':') RunTime,
h.run_duration StepDuration,
case h.run_status when 0 then 'failed'
when 1 then 'Succeded'
when 2 then 'Retry'
when 3 then 'Cancelled'
when 4 then 'In Progress'
end as ExecutionStatus,
h.message MessageGenerated
FROM sysjobhistory h inner join sysjobs j
ON j.job_id = h.job_id
-- name of the job
where j.name='Populate_TTC_Task_Details'
-- only failed jobs
AND h.run_status=0
ORDER BY h.run_date desc

Full Job history
------------------

USE msdb ; 
GO 

EXEC dbo.sp_help_jobhistory 
    @job_name = N'Populate_TTC_Task_Details' ; 
GO

Job names
----------
select s.name,l.name
 from  msdb..sysjobs s
 left join master.sys.syslogins l on s.owner_sid = l.sid
 order by s.name

 -- find guid from backups
use [msdb]
SELECT * FROM log_shipping_primary_databases

"D:\Program Files\Microsoft SQL Server\110\Tools\Binn\sqllogship.exe" -Backup E842CE8C-9F88-4483-B3AE-96BA97F62E25 -server ServerName



Most CPU Intensive Queries
--------------------------

--- https://www.red-gate.com/simple-talk/blogs/how-to-find-cpu-intensive-queries/

SELECT
       -- using statement_start_offset and
       -- statement_end_offset we get the query text
       -- from inside the entire batch
       SUBSTRING(qt.TEXT, (qs.statement_start_offset/2)+1,
                           ((CASE qs.statement_end_offset
                                        WHEN -1 THEN DATALENGTH(qt.TEXT)
                                        ELSE qs.statement_end_offset
                           END
                           - qs.statement_start_offset)/2)+1)
                           as [Text],
qs.execution_count,
qs.total_logical_reads, qs.last_logical_reads,
qs.total_logical_writes, qs.last_logical_writes,
qs.total_worker_time,
qs.last_worker_time,
-- converting microseconds to seconds
qs.total_elapsed_time/1000000 total_elapsed_time_in_S,
qs.last_elapsed_time/1000000 last_elapsed_time_in_S,
qs.last_execution_time,
qp.query_plan
FROM sys.dm_exec_query_stats qs
       -- Retrieve the query text
       CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) qt
       -- Retrieve the query plan
       CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp
ORDER BY qs.total_worker_time DESC -- CPU time


Longest Running queries
-----------------------
SELECT  st.text,
        qp.query_plan,
total_worker_time,
        qs.*
FROM    (
    SELECT  TOP 50 *
    FROM    sys.dm_exec_query_stats
    ORDER BY total_worker_time DESC
) 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.max_worker_time > 300
      OR qs.max_elapsed_time > 300
 
 
Permission
----------
USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'



Server Info
-----------

SELECT
            SERVERPROPERTY('MachineName') AS [ServerName],
SERVERPROPERTY('ServerName') AS [ServerInstanceName],
            SERVERPROPERTY('InstanceName') AS [Instance],
            SERVERPROPERTY('Edition') AS [Edition],
            SERVERPROPERTY('ProductVersion') AS [ProductVersion],
Left(@@Version, Charindex('-', @@version) - 2) As VersionName



Change Recovery Model
---------------------
USE [master]
GO
ALTER DATABASE [Mydb] SET RECOVERY SIMPLE WITH NO_WAIT
GO


Get Recovery Info
-----------------
SELECT name, recovery_model_desc 
   FROM sys.databases 
      WHERE name in ('Mydb')
 
 
 
Shrink Files
---------------

USE [Mydb]
GO
DBCC SHRINKFILE (N'mydb_log' , 0, TRUNCATEONLY)
GO


Update Column uppercase
------------------------

update [MyDB].[myTable].[HostNameCountry]
set hostname=upper(hostname)



database Size
--------------


IF OBJECT_ID('tempdb.dbo.#space') IS NOT NULL
    DROP TABLE #space

CREATE TABLE #space (
      database_id INT PRIMARY KEY
    , data_used_size DECIMAL(18,2)
    , log_used_size DECIMAL(18,2)
)

DECLARE @SQL NVARCHAR(MAX)

SELECT @SQL = STUFF((
    SELECT '
    USE [' + d.name + ']
    INSERT INTO #space (database_id, data_used_size, log_used_size)
    SELECT
          DB_ID()
        , SUM(CASE WHEN [type] = 0 THEN space_used END)
        , SUM(CASE WHEN [type] = 1 THEN space_used END)
    FROM (
        SELECT s.[type], space_used = SUM(FILEPROPERTY(s.name, ''SpaceUsed'') * 8. / 1024)
        FROM sys.database_files s
        GROUP BY s.[type]
    ) t;'
    FROM sys.databases d
    WHERE d.[state] = 0
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')

EXEC sys.sp_executesql @SQL

SELECT
      d.database_id
    , d.name
    , d.state_desc
    , d.recovery_model_desc
    , t.total_size
    , t.data_size
    , s.data_used_size
    , t.log_size
    , s.log_used_size
    , bu.full_last_date
    , bu.full_size
    , bu.log_last_date
    , bu.log_size
FROM (
    SELECT
          database_id
        , log_size = CAST(SUM(CASE WHEN [type] = 1 THEN size END) * 8. / 1024 AS DECIMAL(18,2))
        , data_size = CAST(SUM(CASE WHEN [type] = 0 THEN size END) * 8. / 1024 AS DECIMAL(18,2))
        , total_size = CAST(SUM(size) * 8. / 1024 AS DECIMAL(18,2))
    FROM sys.master_files
    GROUP BY database_id
) t
JOIN sys.databases d ON d.database_id = t.database_id
LEFT JOIN #space s ON d.database_id = s.database_id
LEFT JOIN (
    SELECT
          database_name
        , full_last_date = MAX(CASE WHEN [type] = 'D' THEN backup_finish_date END)
        , full_size = MAX(CASE WHEN [type] = 'D' THEN backup_size END)
        , log_last_date = MAX(CASE WHEN [type] = 'L' THEN backup_finish_date END)
        , log_size = MAX(CASE WHEN [type] = 'L' THEN backup_size END)
    FROM (
        SELECT
              s.database_name
            , s.[type]
            , s.backup_finish_date
            , backup_size =
                        CAST(CASE WHEN s.backup_size = s.compressed_backup_size
                                    THEN s.backup_size
                                    ELSE s.compressed_backup_size
                        END / 1048576.0 AS DECIMAL(18,2))
            , RowNum = ROW_NUMBER() OVER (PARTITION BY s.database_name, s.[type] ORDER BY s.backup_finish_date DESC)
        FROM msdb.dbo.backupset s
        WHERE s.[type] IN ('D', 'L')
    ) f
    WHERE f.RowNum = 1
    GROUP BY f.database_name
) bu ON d.name = bu.database_name
ORDER BY t.total_size DESC


Get size of db from back up file
--------------------------------


-- give the path of backup file
RESTORE FILELISTONLY FROM DISK = N'C:\DB_Backup\Mydb.bak'



Link Server Query
----------------

-- get the details of the linkservers
sp_linkedservers



-- query from link server
-- below is the example
select * from openquery(LInkServerName, 'select * from XXXX.XXV_V')



Session Precheck / any active sessions for DB
---------------------------------------------

BEGIN TRANSACTION
SET NOCOUNT ON
BEGIN
DECLARE @V_COUNT INTEGER

SELECT @V_COUNT = count(*) FROM MASTER..SYSPROCESSES P, MASTER..SYSDATABASES D WHERE P.DBID = D.DBID AND D.DBID = DB_ID('#DBNAME#') and P.SPID <> @@spid and P.SPID > 50;

IF (@V_COUNT > 0)
BEGIN
SELECT SPID,hostname FROM MASTER..SYSPROCESSES P, MASTER..SYSDATABASES D
WHERE P.DBID = D.DBID AND D.DBID = DB_ID('#DBNAME#') and P.SPID <> @@spid;
RAISERROR('',16,1)
ROLLBACK TRANSACTION
RETURN
END
END


Add user
---------

USE [master]
GO
CREATE LOGIN [NEXA\username] FROM WINDOWS WITH DEFAULT_DATABASE=[master]
GO
USE [Mydb]
GO
CREATE USER [NEXA\username] FOR LOGIN [NEXA\username]
GO
USE [Mydb]
GO
EXEC sp_addrolemember N'db_owner', N'NEXA\username'
GO


Check Performance and kill running Scripts
------------------------------------------

sp_who2

kill 74


Shrink DB
------------------


USE [MyDB]
GO
/****** Object:  StoredProcedure [mydb].[Nexa_Shrink_MyDBTrasactionLog]    Script Date: 9/27/2016 12:00:58 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [MyDB].[Nexa_Shrink_MyDBTrasactionLog] 
 
AS 
 
BEGIN 
 -- Declare required variables. 
 DECLARE @vcDBMirroringStatus VARCHAR (100); 
 DECLARE @vcMirroringStatus VARCHAR (100); 
 DECLARE @intDBId INT; 
 
 -- Set the values for variables. 
 
 SET @vcMirroringStatus = 'SYNCHRONIZED' -- This is the syncronized status 
 SET @intDBId = DB_ID();-- This is the digite mirroring DB id. 
 
 -- Get the Digite DB mirroring status 
 SET @vcDBMirroringStatus = (select mirroring_state_desc from sys.database_mirroring where database_id = @intDBId) 
 
 -- If Digite DB mirroring status is 'SYNCHRONIZED' only shrink the DB log 
 IF @vcDBMirroringStatus = @vcMirroringStatus 
 BEGIN 
  CHECKPOINT 
  BACKUP LOG  MyDb to disk = 'C:\ShrinkDBLogs\Mydb1.trn' 
  DBCC SHRINKFILE (Mydb_log, 15360) 
 END 
 
END 




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


SELECT TOP 25
dm_mid.database_id AS DatabaseID,
dm_migs.avg_user_impact*(dm_migs.user_seeks+dm_migs.user_scans) Avg_Estimated_Impact,
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 NULL 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 IS 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



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