2010-05-19 69 views
2

需求說:存儲過程意味着根據5個標識符搜索數據。如果有完全匹配的返回,只有完全匹配,如果不是,但在非空參數上有完全匹配,則返回ONLY這些結果,否則返回任何4個非空參數的匹配項...等等僅返回存儲過程中的最後一個選擇結果

我(簡化)的代碼如下所示:

create procedure xxxSearch @a nvarchar(80), @b nvarchar(80)... 
as 
begin 
    select whatever 
    from MyTable t 
    where ((@a is null and t.a is null) or (@a = t.a)) and 
      ((@b is null and t.b is null) or (@b = t.b))... 

    if @@ROWCOUNT = 0 
    begin 
     select whatever 
      from MyTable t 
      where ((@a is null) or (@a = t.a)) and 
       ((@b is null) or (@b = t.b))... 
      if @@ROWCOUNT = 0 
      begin 
      ... 
      end 
    end 
end 

因此可以有更多套的成績選擇,首當其衝空的,我只需要最後一個。 我知道在應用程序端很容易得到最後一個結果集,但是我們所有的存儲過程調用都經歷了一個框架,該框架期望第一個表中的重要結果,而我並不急於改變它並測試所有現有的SP。

有沒有辦法只從存儲過程中返回最後的選擇結果? 有沒有更好的方法來完成這項任務?

回答

4

使用表變量:

create procedure xxxSearch @a nvarchar(80), @b nvarchar(80)... 
as 
begin 
    DECLARE @res TABLE(...) 
    INSERT INTO @res(...) 
    select whatever 
    from MyTable t 
    where ((@a is null and t.a is null) or (@a = t.a)) and 
      ((@b is null and t.b is null) or (@b = t.b))... 

    if @@ROWCOUNT = 0 
    begin 
     INSERT INTO @res(...) 
     select whatever 
      from MyTable t 
      where ((@a is null) or (@a = t.a)) and 
       ((@b is null) or (@b = t.b))... 
      if @@ROWCOUNT = 0 
      begin 
      ... 
      end 
    end 
    SELECT ... FROM @res 
end 
2

您可以使用本地表變量來保存結果,然後從中選擇,因此只有一個SELECT。

你可以重複你的查詢(你最終能夠擺脫嵌套):

create procedure xxxSearch @a nvarchar(80), @b nvarchar(80)... 
as 
begin 
    IF EXISTS (select whatever 
    from MyTable t 
    where ((@a is null and t.a is null) or (@a = t.a)) and 
      ((@b is null and t.b is null) or (@b = t.b))...) 
    BEGIN 
    select whatever 
     from MyTable t 
     where ((@a is null and t.a is null) or (@a = t.a)) and 
       ((@b is null and t.b is null) or (@b = t.b))... 
    RETURN 
    END 

    etc. 
end 

或者,你可以找到一種方法,所有的查詢組合成一個查詢 - 可能與UNION。

+0

這將是很好能夠標記多個答案。 – 2010-05-19 16:29:50

相關問題