表值函数与标量值函数示例

--内联表值函数
CREATE FUNCTION TEST1
(    
    @ID INT
    )
RETURNS TABLE
AS
RETURN
(
    select * from CN_SingleLogin where id=@ID
)
GO
--执行
select * from TEST1(364)

--多语句表值函数(相当于用Insert语句和表变量来存储查询结果)
CREATE FUNCTION TEST3
(
    @ID INT
)
RETURNS @ReturnTable TABLE
(
    loginId int,
    singlename nvarchar(100),
    singlepassword nvarchar(100),
    email nvarchar(100),
    lastlogindate datetime,
    levelid int
)
AS
BEGIN
    insert into @ReturnTable
    select
    s.id as loginId,
    s.singlename,
    s.singlepassword,
    s.email,
    s.lastlogindate,
    m.levelid
    from CN_SingleLogin as s
    inner join CN_Member_Info as m
    on m.singleid=s.id
    where s.id=@ID
    RETURN
END
GO
--执行
select * from TEST3(364)

--标量值函数
CREATE FUNCTION TEST2
(
    @ID INT
)
RETURNS NVARCHAR(100)
AS
BEGIN
    DECLARE @Name NVARCHAR(100)
    SELECT @Name=singlename from CN_SingleLogin where id=@ID
    RETURN @Name
END
GO
--执行
select dbo.TEST2(364) --需加dbo.

posted @ 2018-10-09 10:06  skybirdzw  阅读(432)  评论(0)    收藏  举报