我正在尝试创建一个SQL函数,以测试参数是否以某个特定术语开头或包含该术语,但不以该术语开头。
基本上,如果参数以术语开头,则函数返回0。否则,返回1。
这是我拥有的功能的核心,我正尝试将其与我发现的另一个功能相适应:
CREATE FUNCTION [dbo].[fnGetRelevance]
(
@fieldName nvarchar(50),
@searchTerm nvarchar(50)
)
RETURNS @value int -- this is showing an error, it seems to expect table but all I want is an int
(
-- does this need to be here? If so, what should it be?
)
AS
BEGIN
declare @field TABLE(Data nvarchar(50))
insert into @field
select Data from @fieldName
if (Data like @searchTerm + '%') -- starts with
begin
return 0
end
else if (Data like '%' + @searchTerm + '%' and Data not like @searchTerm + '%') -- contains, but doesn't start with
begin
return 1
end
END
GO
最佳答案
您无需为返回值提供变量名,只需提供其类型即可,并且不需要括号。
CREATE FUNCTION [dbo].[fnGetRelevance]
(
@fieldName nvarchar(50),
@searchTerm nvarchar(50)
)
RETURNS int
AS
....
还;
select Data from @fieldName
将不起作用,您需要dynamic SQL从名称在变量中的对象中选择。
关于sql - 如何创建SQL Server函数以返回int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6264438/