Using function in SQL Server 在SQL Server中使用函数

Categories: Database; Tagged with: ; @ September 7th, 2012 15:06

Create SQL function:

USE DavidTest;
GO
IF OBJECT_ID ('dbo.fn_isUserActive') IS NOT NULL
    DROP FUNCTION dbo.fn_isUserActive;
GO
CREATE FUNCTION dbo.fn_isUserActive (@userID int)
RETURNS int
WITH EXECUTE AS CALLER
AS
BEGIN
    DECLARE @userStatus int;
    DECLARE @isActive int;
    SELECT @userStatus = ID FROM DavidTest.dbo.DavidUser WHERE ID=@userID ;

    if(@userStatus is not null AND @userStatus = 3)
    BEGIN
        SET @isActive = 1;
    END
    ELSE
        SET @isActive = 0;
RETURN @isActive;
END;
GO

 

Using the function:

SELECT dbo.fn_isUserActive(3);

SELECT * FROM dbo.DavidUser u where dbo.fn_isUserActive(u.ID) > 0;

<->



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.