加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

如何创建SQL Server函数以返回int?

发布时间:2020-12-12 06:33:15 所属栏目:MsSql教程 来源:网络整理
导读:我正在尝试创建一个SQL函数来测试参数是以某个术语开头还是包含该术语,但不是以它开头. 基本上,如果参数以term开头,则函数返回0.否则返回1. 这是我所拥有的函数的骨骼,我正在尝试从我发现的另一个函数中进行调整: CREATE FUNCTION [dbo].[fnGetRelevance] (
我正在尝试创建一个SQL函数来测试参数是以某个术语开头还是包含该术语,但不是以它开头.

基本上,如果参数以term开头,则函数返回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

解决方法

您不为返回值提供变量名称,只提供其类型,并且不需要parens;
CREATE FUNCTION [dbo].[fnGetRelevance] 
(   
    @fieldName nvarchar(50),@searchTerm nvarchar(50)
)

RETURNS int
AS
....

也;

select Data from @fieldName

不起作用,你需要dynamic SQL来从一个变量中名称的对象中进行选择.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读