Tạo function trả về DataTable trong SQL

* Viết trả về DataTable không cần khai báo cột

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        <Author,,Name>
-- Create date: <Create Date,,>
-- Description:    <Description,,>
-- TEST:  Select * From [dbo].[BCKhachhang]()
-- =============================================
ALTER FUNCTION [dbo].[BCKhachhang]
(   

)
RETURNS TABLE
AS
RETURN
(
    -- Add the SELECT statement with parameter references here
    SELECT Ma_KhachHang,Ten_KhachHang,(select sum(Sotien) from tbHoadon where Ma_KhachHang = tbKhachHang.Ma_KhachHang) as Tongtien from tbKhachHang
)
 

Viết hàm function trả về DataTable trong SQL Server
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        <Author,,Name>
-- Create date: <Create Date,,>
-- Description:    <Description,,>
-- =============================================
-- select * From  dbo.fHoSo('1')
ALTER FUNCTION dbo.fHoSo
(   
    -- Add the parameters for the function here
    @Lop nvarchar(50)
)
RETURNS @temp TABLE
(
    Ten nvarchar(50)
,    Lop  nvarchar(60)
)
AS
BEGIN

    Insert @temp values
            (
                    '1'
                ,    '2'
            )

    Insert @temp values
            (
                    '2'
                ,    '3'
            )

    Return;
END
GO

 

Viết hàm function tính tổng DataTable trong SQL Server
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        <Author,,Name>
-- Create date: <Create Date,,>
-- Description:    <Description,,>
-- =============================================
-- select * From  dbo.fHoSo('1')
ALTER FUNCTION dbo.fTong
(   
    -- Add the parameters for the function here
    @a int,
    @b int,
)
RETURNS @temp TABLE
(
    a int
,    b  int
, tong int
)
AS
BEGIN

    Insert @temp values
            (
                   @a
                ,   @b
                , @a+@b
            )

 
    Return;
END
GO