sql-server - 您可以为表指定一个子序列吗?

标签 sql-server tsql sql-server-2012

我创建了一个项目历史记录表,我希望自动递增按 ItemId 分区的 VersionId

ID        ItemId        VersionId        ItemContent        Created
1         1             1                fooo               2015-02-24 12:54:00.11
2         2             1                barr               2015-02-24 12:54:15.35
3         1             2                foo                2015-02-24 12:55:00.61
4         1             3                baz                2015-02-24 12:55:45.23
5         2             2                bar                2015-02-24 12:56:00.03

Currently, that VersionId is set in a trigger. What I would like to find is something like this (I know this doesn't actually work):

create table ItemHistory
(
     Id int identity(1,1) not null primary key
    ,ItemId int not null references Item(Id)
    ,VersionId int not null <b>default row_number() over (partition by ItemId order by Id)</b>
    ,ItemContent varchar(max)
    ,Created datetime not null default getdate()
)

虽然我有一个可行的解决方案,但我想知道我是否缺少一些处理这种情况的内置功能。<​​/p>

最佳答案

如果您想使用我的评论作为答案

为什么不直接用 View 来做呢?您可以在 View 中使用 row_number() 。

有了 ItemId 的索引,Id 应该会非常快。
可能比触发器更少的开销。

我看到您添加了一条只读评论。更多观看理由。

关于sql-server - 您可以为表指定一个子序列吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28703052/

相关文章:

SQL 计算 IP 列中的不同子网

sql-server - 将 nvarchar 列排序为整数

sql - 按 7 天分组日期,不包括特定日期

SQL Server 字符串连接与东西

tsql - 我应该删除假设索引吗?

c# - 将 Binary(16) 转换为 int,在 C# 中结果相同

ssis - Windows 密码每 90 天更改一次,凭据密码不同步且作业失败

没有结束日期的 SQL DateDiff

c++ - MS SQL、C++ 解决方案的最佳全文搜索替代方案

sql-server - 计数记录,除了超过 'N' 的连续值