(SQL) Replaced NOT IN with NOT EXISTS and results differ

ぐ巨炮叔叔 提交于 2019-12-23 05:44:27

问题


Trying to fix someone else's code. The NOT IN kills performance. I took it out and replaced with Not Exists and I'm getting different results. The commented out not in is just above my not exists. Anyone see anything stupid I'm doing here?

IF @ProcessComplete = 1
    BEGIN

--      PRINT 'Group-Complete'
    INSERT INTO @ProcessIDTable
    SELECT DISTINCT(ProcessID)
    FROM vPortalInbox
    WHERE  GroupUserIDs LIKE '%,' + CAST(@UserID AS VARCHAR(MAX)) + ',%' 
    AND StepOwnerID IS NULL

    --AND ProcessID NOT IN (SELECT ProcessID FROM @ProcessIDTable)

    And  not exists (SELECT ProcessID FROM @ProcessIDTable)

回答1:


You could try:

And not exists (
  SELECT ProcessID
  FROM @ProcessIDTable
  WHERE ProcessID = vPortalInbox.ProcessID)

...or possibly even better still: you could try a (left or right) outer join to vPortalInbox on ProcessID, and specify in your WHERE clause that @ProcessIDTable.ProcessID IS NULL:

...
SELECT DISTINCT(ProcessID)
FROM vPortalInbox LEFT OUTER JOIN @ProcessIDTable 
     ON vPortalInbox.ProcessID = @ProcessIDTable.ProcessID 
WHERE  GroupUserIDs LIKE '%,' + CAST(@UserID AS VARCHAR(MAX)) + ',%' 
AND StepOwnerID IS NULL AND @ProcessIDTable.ProcessID IS NULL



回答2:


1 --AND ProcessID NOT IN (SELECT ProcessID FROM @ProcessIDTable)

2 And  not exists (SELECT ProcessID FROM @ProcessIDTable)

The above two statements are not same. The not exist will evaluate to true only when you get no rows from the subquery inside the brackets following the not exists clause. Since you have no conditions for the sub-query following not exists clause, it will never return 0 rows unless the table is empty.

Try using this where clause:

FROM vPortalInbox P1
WHERE  GroupUserIDs LIKE '%,' + CAST(@UserID AS VARCHAR(MAX)) + ',%' 
AND StepOwnerID IS NULL

And  not exists (SELECT 1 FROM @ProcessIDTable P2
                 where  P1.ProcessID = P2.ProcessID  )


来源:https://stackoverflow.com/questions/19824241/sql-replaced-not-in-with-not-exists-and-results-differ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!