簡體   English   中英

存儲在SQL Server中維護排序索引的計算列的最佳方法是什么?

[英]What's the best way to store a computed column that maintains a sorting index in SQL Server?

所以,假設我有一個名為[transactions]的表,其中包含一個標識列作為主鍵,一個日期字段和一些其他列。 我想要包含一個計算或以某種方式計算的持久列,它將有效地存儲“排序順序”。 但是,這不能僅僅是ID列,因為我按日期排序,有時您可能會追溯性地添加值。

例如,如果表開始時看起來像這樣:

+-----+------------+---------+--------+--------+
| id  |    date    | account | amount | (sort) |
+-----+------------+---------+--------+--------+
|   1 | 2014-05-22 |      7  | 100.00 |    1   |
|   2 | 2014-05-29 |      7  |  45.25 |    2   |
|   3 | 2014-06-03 |      8  |  99.00 |    3   |
+-----+------------+---------+--------+--------+

然后,如果我運行此聲明:

INSERT INTO [transactions] ([date], [account], [amount]) 
VALUES ('2014-05-27', 8, 88.50);

我希望sort列足夠智能,以便表格看起來像這樣:

+-----+------------+---------+--------+--------+
| id  |    date    | account | amount | (sort) |
+-----+------------+---------+--------+--------+
|   1 | 2014-05-22 |      7  | 100.00 |    1   |
|   2 | 2014-05-29 |      7  |  45.25 |    3   |
|   3 | 2014-06-03 |      8  |  99.00 |    4   |
|   4 | 2014-05-27 |      8  |  88.50 |    2   |
+-----+------------+---------+--------+--------+

理想情況下,我希望此列保持為實際列。 實現這一目標的最佳方法是什么?

您可以在需要時計算該值:

select t.*, row_number() over (order by [date]) as [sort]
from transactions t;

或者,只需使用[date]作為order by 我不明白為什么需要另一個專欄。

編輯:

如果sort順序保持列sort ,那么您將需要一個觸發器。 並且,觸發器不會便宜。 觸發器中的邏輯基本上是:

update transactions
    set sort = sort + 1
    where [date] > NEWDATE;

insert into transactions( . . . , [sort])
    select . . . , coalesce(max([sort])) + 1
    from transactions
    where [date] < NEWDATE;

(我省略了定義觸發器所涉及的所有內容。)

盡管可以使用索引使insert變得非常高效,但這確實會影響update的性能,這必須影響具有更大日期的每一行。 如果您幾乎總是插入具有較新日期的行,這可能是一個合理的權衡。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM