Mad*_*mir 4 sql-server sql-server-2005
要求表示:存储过程用于根据 5 个标识符搜索数据。如果存在精确匹配,则仅返回精确匹配,如果没有,但非空参数上存在精确匹配,则仅返回这些结果,否则返回任何 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
Run Code Online (Sandbox Code Playgroud)
因此,可以选择更多组结果,第一组为空,我只需要最后一组。我知道在应用程序端获得最后一个结果集很容易,但是我们所有的存储过程调用都通过一个框架,该框架期望第一个表中的重要结果,我并不急于更改它并测试所有现有的 SP。
有没有办法只返回存储过程的最后一个选择结果?有更好的方法来完成这项任务吗?
使用表变量:
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
Run Code Online (Sandbox Code Playgroud)