存储过程返回结果,甚至认为不应该这样做

时间:2018-11-09 09:52:29

标签: sql sql-server sql-server-2008 stored-procedures logical-operators

我有一个存储过程,如下所示:

ALTER PROCDURE [dbo].[zsp_selectallupceans_listProduction]
    (@UPCList NVARCHAR(4000),
     @EANList NVARCHAR(4000),
     @Type TINYINT)
AS
    SELECT  
        dd.UPC, dd.EAN, dd.EBAYID AS ItemID
    FROM
        ThirdPartyData AS dd 
    WHERE 
        EXISTS (SELECT 1 FROM dbo.SplitStringProduction(@UPCList,',') S1 
                WHERE dd.UPC = S1.val) 
        OR EXISTS (SELECT 1 FROM dbo.SplitStringProduction(@EANList,',') S2 
                   WHERE dd.EAN = S2.val) 
        AND dd.Type = @Type

参数传递如下:

@UPCList='709127309019',
@EanList='0709127309019',
@Type=4

“ SplitStringProduction”函数如下所示:

ALTER FUNCTION [dbo].[SplitStringProduction]
    (@string NVARCHAR(MAX),
     @delimiter NVARCHAR(5)) 
RETURNS @t TABLE
           (
                val NVARCHAR(500)
           )
AS
BEGIN
    DECLARE @xml XML
    SET @xml = N'<root><r>' + replace(@string,@delimiter,'</r><r>') + '</r></root>'

    INSERT INTO @t(val)
       SELECT
           r.value('.','varchar(500)') AS item
       FROM
           @xml.nodes('//root/r') as records(r)

    RETURN
END

现在,当我从表中进行简单选择时,如下所示:

select * 
from thirdpartydata dd
where dd.UPC = '709127309019' -- note this is one of the parameters passed to the stored procedure...

在列Type设置为“ 1”的情况下,我只会得到1个结果。...

现在,当我尝试存储过程时:

exec  zsp_selectallupceans_listProduction '709127309019','0709127309019',4

即使我不应该得到任何结果,我仍然会得到1个结果,因为如果您可以看到“ Type”参数设置为4,那么就找不到匹配的记录。...

我在这里做错了什么,我似乎无法弄清楚??

1 个答案:

答案 0 :(得分:2)

您需要将OR条件括在括号内:

WHERE (
      EXISTS (SELECT 1 FROM dbo.SplitStringProduction(@UPCList,',') S1 WHERE dd.UPC=S1.val) 
   OR EXISTS (SELECT 1 FROM dbo.SplitStringProduction(@EANList,',') S2 WHERE dd.EAN=S2.val) 
) AND dd.Type = @Type

没有他们,您的查询是这样的:

WHERE EXISTS (...) 
   OR (EXISTS (...) AND dd.Type = @Type)

得到的结果是因为第一个OR条件匹配。