gpt4 book ai didi

sql-server - VIEW 中的 SUM OVER PARTITION BY 为 NULL,但直接使用时有效

转载 作者:行者123 更新时间:2023-12-03 02:53:54 26 4
gpt4 key购买 nike

在 SQL Server 2016 数据库中,我有一个包含金融交易的表:

CREATE TABLE Transactions
TxnId int NOT NULL IDENTITY(1,1) PRIMARY KEY,
AccountId int NOT NULL,
DateTime datetime NOT NULL,
Amount money NOT NULL
)

我编写了一个VIEW来显示运行余额信息:

CREATE VIEW TransactionsWithBalance AS

SELECT
*,
SUM( Amount ) OVER ( PARTITION BY AccountId ORDER BY [DateTime], TxnId ) AS Balance
FROM
Transactions

当我查询此 View 时,Balance 列包含所有 NULL 值:

SELECT
*
FROM
TransactionsWithBalance

TxnId AccountId DateTime Amount Balance
1 1 2017-01-01 100.00 NULL
2 1 2017-01-02 200.00 NULL
3 2 2017-01-01 10.00 NULL
4 1 2017-01-03 300.00 NULL

但是当我直接在 SSMS 中运行查询(使用 SUM( Amount ) OVER ( PARTITION BY...) )查询时,我在余额中得到了预期值> 栏目。

TxnId    AccountId    DateTime      Amount    Balance
1 1 2017-01-01 100.00 100.00
2 1 2017-01-02 200.00 300.00
3 2 2017-01-01 10.00 10.00
4 1 2017-01-03 300.00 600.00

为什么在 VIEW 内查询时聚合返回 NULL 值?

最佳答案

这是当元数据不同步时可能发生的事情之一,因为您没有:

  • 架构绑定(bind) View ;或
  • 调用 sp_refreshview 每当 View 底层的对象发生变化时

    Remarks

    If a view is not created with schemabinding, sp_refreshview should be run when changes are made to the objects underlying the view that affect the definition of the view. Otherwise, the view might produce unexpected results when it is queried.

更好的选择可能是使用架构绑定(bind)。这也将迫使您不要使用 SELECT *在 View 中,并为表使用由两部分组成的名称,这两种最佳实践:

CREATE VIEW dbo.TransactionsWithBalance
WITH SCHEMABINDING
AS
SELECT
TRN.TxnId,
TRN.AccountId,
TRN.[DateTime],
TRN.Amount,
Balance =
SUM(TRN.Amount) OVER (
PARTITION BY TRN.AccountId
ORDER BY TRN.[DateTime], TRN.TxnId)
FROM
dbo.Transactions AS TRN;

关于sql-server - VIEW 中的 SUM OVER PARTITION BY 为 NULL,但直接使用时有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46550337/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com