从过程中调用函数

时间:2019-09-08 19:14:20

标签: sql-server stored-procedures stored-functions

我无法从过程中调用函数,而且我也不明白为什么。 该功能正在运行,但在程序中却无效。

我尝试编写一些代码来检查用户名是否在我创建的表中已经存在。

--Boolean Function If Username Exists Or Not

CREATE FUNCTION Fun_Exists_Username
    (@Username_to_check VARCHAR(10))
RETURNS INT 
AS
BEGIN
    DECLARE @Boolean BIT

    IF EXISTS (SELECT UserName FROM UTBL_Players WHERE @Username_to_check = UserName)
        SET @Boolean = 1
     ELSE 
        SET @Boolean = 0

     RETURN @Boolean
END

-- Procedure that get username and chek it
CREATE PROCEDURE Usp_Username
    @UserName VARCHAR(10)
AS
BEGIN
    DECLARE @Boolean INT

    SELECT @Boolean = Fun_Exists_Username(@UserName)

    IF @Boolean = 0
        PRINT 'This user name already exists.
            You can use this user name: '   -- function that returns a free username
    ELSE 
        PRINT 'This user name is fine'
END

我收到此错误:

  

消息195,级别15,状态10,过程Usp_Username,第7行[批处理开始第24行]'Fun_Exists_Username'不是公认的内置函数名称。

1 个答案:

答案 0 :(得分:2)

在创建和调用函数时,您必须使用模式前缀。

因此将创建内容更改为:

CREATE FUNCTION dbo.Fun_Exists_Username

并在调用它时使用此:

SELECT @Boolean = dbo.Fun_Exists_Username(@UserName)