forked from SeemaSP/shoppingjquerycart
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path13 - ParameterSniffingDemo.sql
123 lines (99 loc) · 2.44 KB
/
13 - ParameterSniffingDemo.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
-- Demonstration 13 - Parameter Sniffing
USE peoplePS
GO
-- Show query and run to reset demo
ALTER procedure [dbo].[usp_countrysearch]
@country varchar(80)
AS
SELECT p.lastname, p.dob, p.sex, c.country
FROM people p join country c
ON p.personid = c.personid
WHERE c.country = @country
GO
-- Show query plan for UK
DBCC FREEPROCCACHE
GO
EXEC usp_countrysearch 'UK'
GO
-- Show query plan for US
DBCC FREEPROCCACHE
GO
EXEC usp_countrysearch 'US'
GO
-- Don't clear plan cache. Show bad plan and parameter sniffing
EXEC usp_countrysearch 'UK'
GO
-- Options to fix
-- 1 Run stored procedure with recompile
EXEC usp_countrysearch 'UK' WITH RECOMPILE
GO
EXEC usp_countrysearch 'US' WITH RECOMPILE
GO
-- 2 changed stored procedure and use statement level recompile
ALTER procedure [dbo].[usp_countrysearch]
@country varchar(80)
AS
SELECT p.lastname, p.dob, p.sex, c.country
FROM people p join country c
ON p.personid = c.personid
WHERE c.country = @country
OPTION (RECOMPILE);
GO
EXEC usp_countrysearch 'UK'
GO
EXEC usp_countrysearch 'US'
GO
-- 3 changed stored procedure and use optimize for
ALTER procedure [dbo].[usp_countrysearch]
@country varchar(80)
AS
SELECT p.lastname, p.dob, p.sex, c.country
FROM people p join country c
ON p.personid = c.personid
WHERE c.country = @country
OPTION (OPTIMIZE FOR (@country = 'UK') );
GO
DBCC FREEPROCCACHE
GO
EXEC usp_countrysearch 'US'
GO
DBCC FREEPROCCACHE
GO
EXEC usp_countrysearch 'UK'
GO
use AdventureWorks
Go:
SELECT SalesOrderDetailID, OrderQty
FROM Sales.SalesOrderDetail
WHERE ProductID = 897;
SELECT SalesOrderDetailID, OrderQty
FROM Sales.SalesOrderDetail
WHERE ProductID = 945;
SELECT SalesOrderDetailID, OrderQty
FROM Sales.SalesOrderDetail
WHERE ProductID = 870;
go;
CREATE PROCEDURE Get_OrderID_OrderQty
@ProductID INT
AS
SELECT SalesOrderDetailID, OrderQty
FROM Sales.SalesOrderDetail
WHERE ProductID = @ProductID;
EXEC Get_OrderID_OrderQty @ProductID=870;
EXEC Get_OrderID_OrderQty @ProductID=897;
drop PROCEDURE Get_OrderID_OrderQty;
ALTER PROCEDURE Get_OrderID_OrderQty
@ProductID INT
AS
SELECT SalesOrderDetailID, OrderQty
FROM Sales.SalesOrderDetail
WHERE ProductID = @ProductID
OPTION (OPTIMIZE FOR (@ProductID=945));
go
ALTER PROCEDURE Get_OrderID_OrderQty
@ProductID INT
WITH RECOMPILE
AS
SELECT SalesOrderDetailID, OrderQty
FROM Sales.SalesOrderDetail
WHERE ProductID = @ProductID;