SQL Server 2012 内联 table 值函数返回空行

SQL Server 2012 Inline table-valued function returning empty rows

我有一个名为 TaxLots 的 table,它是使用这些列创建的:

CREATE TABLE Portfolio.TaxLots
(
Ticker varchar(22) NOT NULL,
SecurityDescription varchar(50) NOT NULL,
Class varchar(15) NULL,
Ccy varchar(5) NULL,
LSPosition char(3) NULL,
Date date NULL,
Quantity int NULL,
LocAvgCost decimal(8,3) NULL,
LocTaxCostBasis int NULL,
LocMktVal int NULL,
BaseAvgCost decimal(8,3) NULL,
BaseTaxCostBasis int NULL,
BaseMktVal int NULL,
BaseUNRL int NULL,
DateCreated DATE NOT NULL DEFAULT Cast(GetDate() as Date)
)
GO

我想创建一个函数,为最后一个 DateCreated 的特定代码(这将是我的参数)提取其中一些列。我创建了以下函数:

USE FundDB
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION dbo.GetTaxLots
(   
@Ticker varchar
)
RETURNS TABLE 
AS
RETURN 
(
SELECT
    TL.Ticker,
    TL.SecurityDescription,
    TL.LSPosition,
    TL.Date,
    TL.Quantity,
    TL.LocAvgCost,
    TL.LocTaxCostBasis,
    TL.BaseAvgCost,
    TL.BaseTaxCostBasis,
    TL.DateCreated,
    (SELECT SUM(Quantity) 
    FROM
    Portfolio.TaxLots) AS TotalQuantity
FROM
    Portfolio.TaxLots TL
WHERE
    TL.DateCreated= (SELECT Max(TL.DateCreated) FROM Portfolio.TaxLots TL) 
    AND TL.Ticker = @Ticker
)

我用硬编码的 Ticker 单独测试了 SELECT 语句,它给出了我想要的结果,但是当我尝试使用像这样的 SELECT 语句来使用该函数时:

USE FundDB
SELECT *
FROM dbo.GetTaxLots('MSFT')
GO

我得到空行。很困惑。我对此很陌生,所以我觉得我错过了一些明显的东西。

您需要为 @Ticker 变量设置正确的大小

CREATE FUNCTION dbo.GetTaxLots
(   
    @Ticker varchar(22)
)

如果你只使用 @Ticker varchar 变量将只有 1 个字符长,所以当你调用 SELECT * FROM dbo.GetTaxLots('MSFT') 函数中 @Ticker 的值将只是 M

附带说明.. 将您的 2 个子查询组合成一个派生的 table.

可能有助于提高性能
SELECT  TL.Ticker,
        TL.SecurityDescription,
        TL.LSPosition,
        TL.Date,
        TL.Quantity,
        TL.LocAvgCost,
        TL.LocTaxCostBasis,
        TL.BaseAvgCost,
        TL.BaseTaxCostBasis,
        TL.DateCreated,
        IJ.TotalQuantity
FROM    Portfolio.TaxLots TL
        INNER JOIN (SELECT  SUM(Quantity) TotalQuantity, 
                            MAX(DateCreated) MaxCreateDate 
                    FROM    Portfolio.TaxLots ) IJ ON TL.DateCreated = IJ.MaxCreateDate
WHERE   TL.Ticker = @Ticker