2014-03-26 40 views
1

我有MS SQL存儲過程,它旨在返回XML結果,顯示所有申請人爲'sales'MS SQL中的存儲過程搜索參數

頁面上有過濾器可深入搜索結果(sString)。

期望的行爲是:

  • 如果sStringnull,它應該返回所有的結果;
  • 如果sStringnot null,它應該讓sString來顯示找到的字段。

SP無法按預期工作:它始終返回所有結果,無論sString值如何。

MS SQL的SP代碼:

WITH OrderedMatches AS 
(

    SELECT ROW_NUMBER() OVER (ORDER BY MB.Member_Registered DESC) AS RowNumber, 
    MB.Member_ID, 
    MB.Member_Name, MB.Member_Mobile, MB.Member_Propertytosell, MB.Member_Propertytosell_Details, MB.Member_ExistingBuytoLet, MB.Member_TalkingPoints, 
    MB.Member_Registered, MB.Member_Funding, MB.Member_Active, MB.Member_Last_Contacted, MB.Member_Situation 

    FROM dbo.Member_Base MB INNER JOIN dbo.Member_Criteria MC ON MC.Member_ID = MB.Member_ID 

    WHERE MB.Member_Active = 1 AND MC.Criteria_Section = 'sales' 
    AND (
     @sType = 'a' 
     OR (
      @sType = 'b' AND MB.Member_Propertytosell = 1 
     ) 
     OR (
      @sType = 'c' AND MB.Member_ExistingBuytoLet = 1 
     ) 

    ) 
    OR (
     MB.Member_Name LIKE '%' + @sString + '%' OR MB.Member_Mobile LIKE '%' + @sString + '%' OR MB.Member_Propertytosell_Details LIKE '%' + @sString + '%' 
    ) 

)  

SELECT 
(
    SELECT 
     OM.Member_ID as "@id", 
     OM.Member_Name as "@appname", 
     OM.Member_Mobile as "@contact", 
     OM.Member_Propertytosell as "@propts", 
     OM.Member_Propertytosell_Details as "@proptsdetails", 
     OM.Member_ExistingBuytoLet as "@existingBTL", 
     OM.Member_TalkingPoints as "@talkingpoints", 
     OM.Member_Registered as "@registered", 
     OM.Member_Funding as "@funding", 
     OM.Member_Active as "@active", 
     OM.Member_Last_Contacted as "@lastcontact", 
     OM.Member_Situation as "@situation" 

    FROM OrderedMatches OM 

    WHERE OM.RowNumber Between @nstart AND @nend 
    FOR XML path ('applicant'), TYPE 
), 
(
    SELECT COUNT(*) as "@titems" 
    FROM OrderedMatches 
    FOR XML path ('meta') 
) 
FOR XML PATH ('') 


END 

我假設SP是錯誤的,但不能看到哪個部分完全吻合。

有沒有人有任何建議?

回答

0

它會返回所有內容,因爲您的條件與WHERE中的其他條件之間的條件爲sString。將您的WHERE條款更改爲:

WHERE MB.Member_Active = 1 AND MC.Criteria_Section = 'sales' 
AND (
    @sType = 'a' 
    OR (
     @sType = 'b' AND MB.Member_Propertytosell = 1 
    ) 
    OR (
     @sType = 'c' AND MB.Member_ExistingBuytoLet = 1 
    ) 

) 
AND (@sString IS NULL 
    OR 
    (
     MB.Member_Name LIKE '%' + @sString + '%' OR MB.Member_Mobile LIKE '%' + @sString + '%' OR MB.Member_Propertytosell_Details LIKE '%' + @sString + '%' 
    ) 
)