SQL Server Query hangs using parameter in WHERE clause

qq24tv8q  于 2023-04-10  发布在  其他
关注(0)|答案(2)|浏览(118)

I am having difficulty understanding a query here. My query ultimately returns a result set in a report where you can specify a Person in the parameter to view their data. I am joining my Dimension table to my Employee table to return the Name from the Employee table. It looks something like this

Declare @PM varchar(30)
Set @PM = 'John Smith'

SELECT....FullName, EmployeeID, .... 
FROM...
Inner Join EmployeesT on emp.EmployeeNumber = DimP.PersonID
WHERE FullName in (@PM)

Note: My Employee table is in nvarchar and Dimension is is varchar but i dont think that matters as the join still works.

Now, I set a parameter up at the top for testing.

Here is my issue: If I switch the WHERE clause to say WHERE DimP.PersonID IN ('12345') my query takes 3 seconds to run. When I change the query to WHERE FullName in (@PM) the query is taking forever to run; it hangs and runs for 5+ minuets. Has anyone experienced a similar issue?

The result set produces the correct data with multiple "people" and I want to test this by specifying a person, not an id, but when I change the parameter to the Name the query hangs..

lp0sw83n

lp0sw83n1#

It might be parameter sniffing. It is hanging onto the optimized execution plan for another parameter value. Try using OPTION (OPTIMIZE FOR (@parm UNKNOWN)) at the end of your query.

Declare @PM varchar(30)
Set @PM = 'John Smith'

SELECT....FullName, EmployeeID, .... 
FROM...
Inner Join EmployeesT on emp.EmployeeNumber = DimP.PersonID
WHERE FullName in (@PM)

OPTION (OPTIMIZE FOR (@PM UNKNOWN))
8zzbczxx

8zzbczxx2#

My coworker was able to solve this, she used

WHERE emp.empNumber = (CASE WHEN emp.FullName IN (@PM) )

相关问题