创建一个返回表SQL的函数

时间:2016-07-01 19:53:57

标签: sql-server sql-function

我正在创建一个在SQL中返回表的函数,但是,我不知道如何创建函数,我现在的函数是:

CREATE FUNCTION fn_PegaDetalhesDoPagador (  @IdLoteDet bigint )
RETURNS TABLE 
(
    NomeSacado varchar(60),
    CNPJSacado varchar(20),
    Compromisso varchar(25)
)
AS
RETURN 
(
    SELECT  Sacados.NomeSac, 
        LoteDet.IdLoteDet,
        LoteDet.NossoNum,
        LoteDet.Comprom,
        dbo.Sacados.CNPJ
    FROM    dbo.LoteDet INNER JOIN dbo.Sacados ON dbo.LoteDet.IDSac = dbo.Sacados.IDSac
    WHERE idlotedet=@IdLoteDet

    IF @@ROWCOUNT = 0
        BEGIN
            SELECT  Sacados.NomeSac, 
            LoteDetPg.IdLoteDet,
            LoteDetPg.NossoNum,
            LoteDetPg.Comprom,
            dbo.Sacados.CNPJ
            FROM    dbo.LoteDetPg INNER JOIN dbo.Sacados ON dbo.LoteDetPg.IDSac = dbo.Sacados.IDSac
            WHERE idlotedet=@IdLoteDet
            RETURN
        END
    else
        RETURN
)

我需要的是,如果select从表LoteDet中没有返回任何内容,我需要比函数执行表LoteDetPg中的select。

使用这种功能可以做到这一点吗?

使用其他方法可以做到这一点吗?

2 个答案:

答案 0 :(得分:1)

试试这个:

CREATE FUNCTION fn_PegaDetalhesDoPagador ( @IdLoteDet BIGINT )
RETURNS @res TABLE
(
  NomeSacado VARCHAR(60) ,
  IdLoteDet VARCHAR(MAX) ,--check this cols data type
  NossoNum VARCHAR(MAX) ,--check this cols data type
  Compromisso VARCHAR(25) ,
  CNPJSacado VARCHAR(20)
)
AS
BEGIN
    IF EXISTS ( SELECT TOP 1 Sacados.NomeSac --better if you replace this with PK col
                FROM    dbo.LoteDet
                        INNER JOIN dbo.Sacados ON dbo.LoteDet.IDSac = dbo.Sacados.IDSac
                WHERE   idlotedet = @IdLoteDet )
        BEGIN
            INSERT  INTO @res
                    SELECT  Sacados.NomeSac ,
                            LoteDet.IdLoteDet ,
                            LoteDet.NossoNum ,
                            LoteDet.Comprom ,
                            dbo.Sacados.CNPJ
                    FROM    dbo.LoteDet
                            INNER JOIN dbo.Sacados ON dbo.LoteDet.IDSac = dbo.Sacados.IDSac
                    WHERE   IdLoteDet = @IdLoteDet;
        END;
    ELSE
        BEGIN
            INSERT  INTO @res
                    SELECT  Sacados.NomeSac ,
                            LoteDetPg.IdLoteDet ,
                            LoteDetPg.NossoNum ,
                            LoteDetPg.Comprom ,
                            dbo.Sacados.CNPJ
                    FROM    dbo.LoteDetPg
                            INNER JOIN dbo.Sacados ON dbo.LoteDetPg.IDSac = dbo.Sacados.IDSac
                    WHERE   IdLoteDet = @IdLoteDet;
        END;

    RETURN;
END;

答案 1 :(得分:0)

首先从LoteDet表中选择数据计数并存储到变量中,如果变量count不为零,则从LoteDet获取数据,否则使用LoteDetPg表获取数据