Skip to content

Commit bbd924b

Browse files
authored
Add files via upload
1 parent cb4d1cb commit bbd924b

File tree

76 files changed

+26447
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

76 files changed

+26447
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/*
2+
Author: Bert Wagner
3+
Source link: https://blog.bertwagner.com/warning-are-your-queries-vulnerable-to-sql-injection-db914fb39668
4+
*/
5+
6+
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
7+
8+
SELECT
9+
ROUTINE_CATALOG
10+
, ROUTINE_SCHEMA
11+
, ROUTINE_NAME
12+
, ROUTINE_TYPE
13+
, ROUTINE_DEFINITION
14+
FROM
15+
INFORMATION_SCHEMA.ROUTINES
16+
WHERE
17+
REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(ROUTINE_DEFINITION,CHAR(0),''),CHAR(9),''),CHAR(10),''),CHAR(11),''),CHAR(12),''),CHAR(13),''),CHAR(14),''),CHAR(160),''),' ','')
18+
LIKE '%+@%'
19+
AND
20+
( -- Only if executes a dynamic string
21+
ROUTINE_DEFINITION LIKE '%EXEC(%'
22+
OR ROUTINE_DEFINITION LIKE '%EXECUTE%'
23+
OR ROUTINE_DEFINITION LIKE '%sp_executesql%'
24+
);

Scripts/Queries_with_parallelism.sql

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/*
2+
Author: Eitan Blumin
3+
Source link: http://www.madeiradata.com/cost-threshold-for-parallelism-and-how-to-increase-it-properly/
4+
*/
5+
6+
DECLARE
7+
@MinUseCount INT = 50 -- Set minimum usecount to ignore rarely-used plans
8+
, @CurrentCostThreshold FLOAT = 5 -- Serves as minimum sub-tree cost
9+
, @MaxSubTreeCost FLOAT = 30 -- Set the maximum sub-tree cost, plans with higher cost than this wouldn't normally interest us
10+
11+
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
12+
13+
SELECT @CurrentCostThreshold = CONVERT(FLOAT, value_in_use)
14+
FROM sys.configurations
15+
WHERE [name] = 'cost threshold for parallelism';
16+
17+
WITH XMLNAMESPACES
18+
(DEFAULT 'http://schemas.microsoft.com/sqlserver/2004/07/showplan')
19+
SELECT *
20+
FROM
21+
(
22+
SELECT
23+
ecp.plan_handle,
24+
CompleteQueryPlan = query_plan,
25+
StatementText = n.value('(@StatementText)[1]', 'VARCHAR(4000)'),
26+
StatementSubTreeCost = n.value('(@StatementSubTreeCost)[1]', 'VARCHAR(128)'),
27+
ParallelSubTreeXML = n.query('.'),
28+
ecp.usecounts,
29+
ecp.size_in_bytes,
30+
RankPerText = ROW_NUMBER() OVER (PARTITION BY n.value('(@StatementText)[1]', 'VARCHAR(4000)') ORDER BY ecp.usecounts DESC)
31+
FROM sys.dm_exec_cached_plans AS ecp
32+
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS eqp
33+
CROSS APPLY query_plan.nodes('/ShowPlanXML/BatchSequence/Batch/Statements/StmtSimple') AS qn(n)
34+
WHERE n.query('.').exist('//RelOp[@PhysicalOp="Parallelism"]') = 1
35+
AND ecp.usecounts > @MinUseCount
36+
AND n.value('(@StatementSubTreeCost)[1]', 'float') BETWEEN @CurrentCostThreshold AND @MaxSubTreeCost
37+
) AS Q
38+
WHERE
39+
RankPerText = 1 -- This would filter out duplicate statements, returning only those with the highest usecount
40+
ORDER BY
41+
usecounts DESC;

Scripts/QueryActiveDirectory.sql

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/*
2+
Author: Ryan Adams
3+
Original link: http://www.ryanjadams.com/2016/03/query-active-directory-sql-server/
4+
*/
5+
6+
--There are 2 ways to query AD from SQL Server.  The first is using OPENROWSET and the second is using OPENQUERY which requires a linked server.
7+
8+
/*** OPENROWSET METHOD ***/
9+
--You have to enable Ad Hoc Distributed Queries to use OPENROWSET.  Note the OPENQUERY does NOT require this to be enabled since it uses Linked servers.
10+
11+
sp_configure 'show advanced options', 1;
12+
RECONFIGURE;
13+
GO
14+
sp_configure 'Ad Hoc Distributed Queries', 1;
15+
RECONFIGURE;
16+
GO
17+
sp_configure 'show advanced options', 0;
18+
RECONFIGURE;
19+
GO
20+
21+
SELECT DisplayName
22+
FROM OPENROWSET('ADSDSOOBJECT','adsdatasource','SELECT displayName
23+
FROM ''LDAP://mydomainFQDN.com/ou=mySubOU,ou=myTopOU,dc=mychilddomain,dc=myTLdomain,dc=com''
24+
WHERE objectClass = ''User'' ')
25+
26+
/*** OPENQUERY METHOD ***/
27+
--Here is where we create our Linked Server connection to AD
28+
EXEC master.dbo.sp_addlinkedserver @server = N'AD', @srvproduct=N'Active Directory Services Interface', @provider=N'ADsDSOObject', @datasrc=N'adsdatasource'
29+
GO
30+
31+
EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname = N'AD', @locallogin = NULL , @useself = N'True'
32+
GO
33+
34+
--Here is the query using the above created Linked server
35+
SELECT displayName FROM OpenQuery (AD,
36+
'SELECT displayName
37+
FROM ''LDAP://mydomainFQDN.com/ou=mySubOU,ou=myTopOU,dc=mychilddomain,dc=myTLdomain,dc=com''
38+
WHERE objectClass = ''User'' ')
39+
GO
40+
41+
--Here we delete our Linked Server
42+
EXEC master.dbo.sp_dropserver @server=N'AD', @droplogins='droplogins'
43+
GO

Scripts/Query_Store_Export.sql

Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
/*
2+
<documentation>
3+
<summary>dump the previous 8 hours of data from Query Store</summary>
4+
<returns>1 query set</returns>
5+
<issues>No</issues>
6+
<created>2020-01-24 by Greg Gonzalez</created>
7+
<version>1.0</version>
8+
<originalLink>https://sqlperformance.com/2020/01/sql-performance/why-waits-alone-are-not-enough</originalLink>
9+
<sourceLink>https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Query_Store_Export.sql</sourceLink>
10+
</documentation>
11+
*/
12+
13+
DECLARE @HoursBack smallint = 8;
14+
DECLARE @StartDate datetime2 = DATEADD(hour, -@HoursBack, GETUTCDATE());
15+
16+
WITH QueryRuntimeStats AS (
17+
SELECT
18+
p.plan_id
19+
,q.query_id
20+
,q.query_hash
21+
,SUM(rs.count_executions) AS total_executions
22+
,SUM(rs.count_executions * rs.avg_duration) / 1000 AS total_duration_ms
23+
,SUM(rs.count_executions * rs.avg_cpu_time) / 1000 AS total_cpu_ms
24+
,SUM(rs.count_executions * rs.avg_clr_time) / 1000 AS total_clr_time_ms
25+
,SUM(rs.count_executions * rs.avg_query_max_used_memory) AS total_query_max_used_memory
26+
,SUM(rs.count_executions * rs.avg_logical_io_reads) AS total_logi_reads
27+
,SUM(rs.count_executions * rs.avg_logical_io_writes) AS total_logi_writes
28+
,SUM(rs.count_executions * rs.avg_physical_io_reads) AS total_phys_reads
29+
,SUM(rs.count_executions * rs.avg_rowcount) AS total_rowcount
30+
,SUM(rs.count_executions * rs.avg_log_bytes_used) AS total_log_bytes_used
31+
,SUM(rs.count_executions * rs.avg_tempdb_space_used) AS total_tempdb_space_used
32+
from sys.query_store_plan p
33+
join sys.query_store_query q
34+
on q.query_id = p.query_id
35+
join sys.query_store_runtime_stats rs
36+
on rs.plan_id = p.plan_id
37+
join sys.query_store_runtime_stats_interval rsi
38+
on rsi.runtime_stats_interval_id = rs.runtime_stats_interval_id
39+
where rsi.start_time > @StartDate
40+
group by
41+
p.plan_id
42+
,q.query_id
43+
,q.query_hash
44+
)
45+
,QueryWaitStats AS (
46+
SELECT
47+
p.plan_id
48+
,q.query_id
49+
,q.query_hash
50+
,ws.wait_category_desc
51+
,SUM(ws.total_query_wait_time_ms) AS total_wait_time_ms
52+
FROM sys.query_store_plan p
53+
JOIN sys.query_store_query q
54+
ON q.query_id = p.query_id
55+
JOIN sys.query_store_wait_stats ws
56+
ON ws.plan_id = p.plan_id
57+
JOIN sys.query_store_runtime_stats_interval rsi
58+
ON rsi.runtime_stats_interval_id = ws.runtime_stats_interval_id
59+
WHERE rsi.start_time > @StartDate
60+
GROUP BY
61+
p.plan_id
62+
,q.query_id
63+
,q.query_hash
64+
,ws.wait_category_desc
65+
)
66+
,QueryWaitStatsByCategory
67+
AS
68+
(
69+
SELECT *
70+
FROM QueryWaitStats
71+
PIVOT
72+
(
73+
SUM(total_wait_time_ms)
74+
FOR wait_category_desc IN
75+
(
76+
[Unknown]
77+
,[CPU]
78+
,[Worker Thread]
79+
,[Lock]
80+
,[Latch]
81+
,[Buffer Latch]
82+
,[Buffer IO]
83+
,[Compilation]
84+
,[SQL CLR]
85+
,[Mirroring]
86+
,[Transaction]
87+
,[Idle]
88+
,[Preemptive]
89+
,[Service Broker]
90+
,[Tran Log IO]
91+
,[Network IO]
92+
,[Parallelism]
93+
,[Memory]
94+
,[User Wait]
95+
,[Tracing]
96+
,[Full Text Search]
97+
,[Other Disk IO]
98+
,[Replication]
99+
,[Log Rate Governor]
100+
)
101+
) AS pvt
102+
)
103+
,QueryWaitStatsTotals
104+
AS
105+
(
106+
SELECT
107+
plan_id
108+
,query_id
109+
,query_hash
110+
,SUM(total_wait_time_ms) AS total_wait_time_ms
111+
FROM QueryWaitStats
112+
GROUP BY
113+
plan_id
114+
,query_id
115+
,query_hash
116+
)
117+
SELECT
118+
rs.plan_id
119+
, rs.query_id
120+
, rs.query_hash
121+
, rs.total_executions
122+
, rs.total_duration_ms
123+
, rs.total_cpu_ms
124+
, rs.total_clr_time_ms
125+
, rs.total_query_max_used_memory
126+
, rs.total_logi_reads
127+
, rs.total_logi_writes
128+
, rs.total_phys_reads
129+
, rs.total_rowcount
130+
, rs.total_log_bytes_used
131+
, rs.total_tempdb_space_used
132+
, ws.total_wait_time_ms
133+
, wsc.[CPU]
134+
, wsc.[Lock]
135+
, wsc.[Latch]
136+
, wsc.[Buffer Latch]
137+
, wsc.[Buffer IO]
138+
, wsc.[Memory]
139+
, wsc.[Tran Log IO]
140+
, wsc.[Network IO]
141+
, wsc.[Worker Thread]
142+
, wsc.[Unknown]
143+
, wsc.[Compilation]
144+
, wsc.[SQL CLR]
145+
, wsc.[Mirroring]
146+
, wsc.[Transaction]
147+
, wsc.[Idle]
148+
, wsc.[Preemptive]
149+
, wsc.[Service Broker]
150+
, wsc.[Parallelism]
151+
, wsc.[User Wait]
152+
, wsc.[Tracing]
153+
, wsc.[Full Text Search]
154+
, wsc.[Other Disk IO]
155+
, wsc.[Replication]
156+
, wsc.[Log Rate Governor]
157+
FROM QueryRuntimeStats rs
158+
LEFT JOIN QueryWaitStatsTotals AS ws
159+
ON rs.plan_id = ws.plan_id
160+
AND rs.query_id = ws.query_id
161+
LEFT JOIN QueryWaitStatsByCategory AS wsc
162+
ON rs.plan_id = wsc.plan_id
163+
AND rs.query_id = wsc.query_id;

Scripts/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Usefull SQL Server Scripts
2+
3+
More than 100 useful scripts for SQL Server

Scripts/Read_Default_Trace.sql

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/*
2+
<documentation>
3+
<summary>Dynamically generate GRANTs.</summary>
4+
<returns>PRINT dynamically generated GRANTs for user.</returns>
5+
<created>2020-03-02 by Aaron Bertrand</created>
6+
<modified>2020-03-05 by Konstantin Taranov</modified>
7+
<version>1.1</version>
8+
<sourceLink>https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Read_Default_Trace.sql</sourceLink>
9+
<originalLink>https://sqlperformance.com/2020/03/extended-events/removing-default-trace-1</originalLink>
10+
</documentation>
11+
*/
12+
13+
14+
IF OBJECT_ID('tempdb..#t','U') IS NOT NULL DROP TABLE #t;
15+
GO
16+
17+
WITH filesrc ([path]) AS
18+
(
19+
SELECT REVERSE(SUBSTRING(p, CHARINDEX(N'\', p), 260)) + N'log.trc'
20+
FROM (SELECT REVERSE([path]) FROM sys.traces WHERE is_default = 1) s(p)
21+
),
22+
tracedata AS
23+
(
24+
SELECT Context = CASE
25+
WHEN DDL = 1 THEN
26+
CASE WHEN LEFT(ObjectName,8) = N'_WA_SYS_'
27+
THEN 'AutoStat: ' + DBType
28+
WHEN LEFT(ObjectName,2) IN (N'PK', N'UQ', N'IX') AND ObjectName LIKE N'%[_#]%'
29+
THEN UPPER(LEFT(ObjectName,2)) + ': tempdb'
30+
WHEN ObjectType = 17747 AND ObjectName LIKE N'TELEMETRY%'
31+
THEN 'Telemetry'
32+
ELSE 'Other DDL in ' + DBType END
33+
WHEN EventClass = 116 THEN
34+
CASE WHEN TextData LIKE N'%checkdb%' THEN 'DBCC CHECKDB'
35+
-- several more of these ...
36+
ELSE UPPER(CONVERT(nchar(32), TextData)) END
37+
ELSE DBType END,
38+
EventName = CASE WHEN DDL = 1 THEN 'DDL' ELSE EventName END,
39+
EventSubClass,
40+
EventClass,
41+
StartTime
42+
FROM
43+
(
44+
SELECT DDL = CASE WHEN t.EventClass IN (46,47,164) THEN 1 ELSE 0 END,
45+
TextData = LOWER(CONVERT(nvarchar(512), t.TextData)),
46+
EventName = e.[name],
47+
t.EventClass,
48+
t.EventSubClass,
49+
ObjectName = UPPER(t.ObjectName),
50+
t.ObjectType,
51+
t.StartTime,
52+
DBType = CASE WHEN t.DatabaseID = 2 OR t.ObjectName LIKE N'#%' THEN 'tempdb'
53+
WHEN t.DatabaseID IN (1,3,4) THEN 'System database'
54+
WHEN t.DatabaseID IS NOT NULL THEN 'User database' ELSE '?' END
55+
FROM filesrc CROSS APPLY sys.fn_trace_gettable(filesrc.[path], DEFAULT) AS t
56+
LEFT OUTER JOIN sys.trace_events AS e ON t.EventClass = e.trace_event_id
57+
) AS src WHERE (EventSubClass IS NULL)
58+
OR (EventSubClass = CASE WHEN DDL = 1 THEN 1 ELSE EventSubClass END) -- ddl_phase
59+
)
60+
SELECT @@SERVERNAME AS "Instance",
61+
EventName,
62+
Context,
63+
EventCount = COUNT(*),
64+
FirstSeen = MIN(StartTime),
65+
LastSeen = MAX(StartTime)
66+
INTO #t FROM tracedata
67+
GROUP BY GROUPING SETS ((), (EventName, Context));
68+
69+
SELECT * FROM #t ORDER BY EventCount DESC;

0 commit comments

Comments
 (0)