编写存储过程以在具有可选输入参数的列中搜索匹配值

Writing a Stored procedure to search for matching values in columns with optional Input parameters

要求: 编写存储过程,使存储过程中传递的值与 table 中列中的值相匹配,然后排列为从最高到最低的匹配数 attributes.Then 被插入到存储过程中动态创建的临时 table 中。

问题:

我说了 15-20 个匹配的属性,以确认为响应记录搜索而提出的建议。基本上,有一个 table 存储患者信息,并且可以将多个参数传递到存储过程中进行搜索,以便创建一个临时 table 以匹配属性的降序建议记录。

为了构建基本结构,我尝试使用 3 个属性和相应的存储过程来匹配它们,这些存储过程又根据输入参数列表从调用过程中共同调用,进而创建所需的临时 table.

这是 SQL 代码(只是为了说明我到目前为止所尝试的要点):

但事实上,我意识到这太天真了,无法用于可能需要 80-90% accuracy.So 的实时应用程序,究竟什么可以取代这种技术效率更高?

Create Procedure NameMatch 
(
@Name nvarchar(20),
@PercentContribution nvarchar(4) OUT, @PatientName nvarchar(20) out
)
As
declare @temp int 
DECLARE @Query nvarchar(500)
   if Exists(select Name from dbo.PatientDetails where Name = @Name)
   Begin
   set @PatientName = @Name
   set @query = 'select * from dbo.PatientDetails where Name =' +  @Name
   set @temp = 0.1*100
   set @PercentContribution = @temp + '%'
   Execute(@query)
   Return
End

Create Procedure AgeMatch 
(
@Name nvarchar(20),
@Age int,
@PercentContribution nvarchar(4) OUT, @PatientName nvarchar(20) out
)
As
declare @temp int 
DECLARE @Query nvarchar(500)
   if Exists(select Name from dbo.PatientDetails where Name =@Name and Age = + @Age)
   Begin
   set @PatientName = @Name
   set @query = 'select * from dbo.PatientDetails where Name = ' + @Name + ' and Age = '+ @Age
   set @temp = 0.2*100
   set @PercentContribution = @temp + '%'
   Execute(@query)
   Return
End

Create Procedure Nationality 
(
@Name nvarchar(20),
@Age int,
@Nation nvarchar(10),
@PercentContribution nvarchar(4) OUT, @PatientName nvarchar(20) out
)
As
declare @temp int 
DECLARE @Query nvarchar(500)
   if Exists(select Name from dbo.PatientDetails where Name = @Name and Age = @Age and Nationality = @Nation )
   Begin
   set @PatientName = @Name
   set @query = 'select * from dbo.PatientDetails where Name = ' + @Name + ' and Age  = '+ @Age + ' and Nationality = ' + @Nation
   set @temp = 0.3*100
   set @PercentContribution = @temp + '%'
   Execute(@query)
   Return
End

create procedure CallingProcedure
(
@Name nvarchar(20),
@Age int = null,
@Nation nvarchar(10)=  null
)
As 
declare @PercentMatch nvarchar(4)
Begin
create table #results(PatientName nvarchar(30), PercentMatch nvarchar(4))
if(@Nation IS NOT NULL)
Insert into #results exec Nationality @Nation, @Name output, @PercentMatch output
else if(@Age is not Null)
Insert into #results exec AgeMatch @Age, @Name output, @PercentMatch output
else
Insert into #results exec NameMatch @Name, @Name output, @PercentMatch output
End

抛开存储过程语法的细微差别,给定参数 1-n,如果不为空,则应匹配列 1-n 并且结果首先按最大匹配数排序,不需要动态查询 - 普通 SQL 可以做到。

select *
from patient
where @param1 is null or column1 = @param1
or @param2 is null or column2 = @param2
...
or @paramN is null or columnN = @paramN
order by if(column1 = @param1, 1, 0)
    + if(column2 = @param2, 1, 0)
    ...
    + if(columnN = @paramN, 1, 0) desc