我的参数变量在 T-SQL 函数中放在哪里?

Where do my parameter variables go in T-SQL function?

这是我在下面尝试使用两个参数和一个匹配词输出的函数。我使用@searchentry 和@bestmatch 作为我的参数。我的问题是参数应该放在函数中的什么地方,这样我就可以在函数创建时调用它 Select dbo.FunMatch('enamel cleaner', 'cleaner') 它将执行函数和 return 来自两个参数的匹配词,即 1 ?

Create Function dbo.FunMatch(
    @searchentry varchar,
    @bestmatch varchar
    ) 
    Returns INT
    As
    Begin
    Declare @output INT
    Set @output = (select
    @searchentry,
    @bestmatch,
    cast(count(isMatch) as float) as matchingWords
from
(
    select 
        s.value as word_from_search_entry_txt, 
        b.value as word_from_best_match,
        case 
            when s.value = b.value or s.value+'s'=b.value or s.value=b.value+'s' then 'match' 
            else null 
        end as isMatch,
        t.*
     from (
        SELECT 
            @searchentry,@bestmatch
        FROM #tmp_parts
        
    ) t
    cross apply 
    string_split(@searchentry, ' ') s
    cross apply
    string_split(@bestmatch, ' ') b
) a
group by
    @searchentry,
    @bestmatch)
        
        Return @output

我正在编写一个函数来 return 两个字符串之间的匹配词。 示例 数据如下

CREATE TABLE #tmp_parts
(
search_entry_txt VARCHAR(30),
best_match VARCHAR(30),
);
INSERT INTO #tmp_parts
VALUES ('rotating conveyors', 'conveyor'),
('rivet tool', 'rivet nut tool'),
('enamel cleaner', 'cleaner'),
('farm ring', 'ring'),
('tire gauge', 'gauge'),
('ice cream','ice cream');

你可以在这里看到预期的匹配词列

select
    search_entry_txt,
    best_match,
    cast(count(isMatch) as float) as matchingWords
from
(
    select 
        s.value as word_from_search_entry_txt, 
        b.value as word_from_best_match,
        case 
            when s.value = b.value or s.value+'s'=b.value or s.value=b.value+'s' then 'match' 
            else null 
        end as isMatch,
        t.*
     from (
        SELECT 
            search_entry_txt,best_match
        FROM #tmp_parts
    ) t
    cross apply 
    string_split(search_entry_txt, ' ') s
    cross apply
    string_split(best_match, ' ') b
) a
group by
    search_entry_txt,
    best_match

您的函数脚本存在一些问题。

  1. 参数@searchentry@bestmatch可能会添加类型长度,否则会将长度声明为1。
  2. 您在函数末尾缺少 END
  3. 从您的代码中您不需要使用 #tmp_parts temp table,只需使用参数 @searchentry@bestmatch.
  4. 有一些您可能不需要的冗长脚本,(group by 部分,子查询可以使用聚合函数代替)

我重写了你的脚本,你可以试试这个。

Create Function dbo.FunMatch(
    @searchentry varchar(max),
    @bestmatch varchar(max)
) 
Returns INT
As
Begin
    Declare @output INT
    set @output =(select 
    COUNT(case 
        when s.value = b.value or s.value+'s'=b.value or s.value=b.value+'s' then 'match' 
        else null 
    end) 
    from 
    string_split(@searchentry, ' ') s
    cross apply
    string_split(@bestmatch, ' ') b)
    Return @output
END

sqlfiddle