也许这会做:
declare @UserProject as Table
( UserProjectId Int Identity, UserId Int, UserProjectName VarChar(32), UserProjectNumber Int );
insert into @UserProject ( UserId, UserProjectName, UserProjectNumber ) values
( 2, 'Test', ( select IsNull( Max( UserProjectNumber ), 0 ) + 1 from @UserProject where UserId = 2 ) );
insert into @UserProject ( UserId, UserProjectName, UserProjectNumber ) values
( 2, 'Alpha', ( select IsNull( Max( UserProjectNumber ), 0 ) + 1 from @UserProject where UserId = 2 ) );
insert into @UserProject ( UserId, UserProjectName, UserProjectNumber ) values
( 1, 'Aleph', ( select IsNull( Max( UserProjectNumber ), 0 ) + 1 from @UserProject where UserId = 1 ) );
insert into @UserProject ( UserId, UserProjectName, UserProjectNumber ) values
( 2, 'Beta', ( select IsNull( Max( UserProjectNumber ), 0 ) + 1 from @UserProject where UserId = 2 ) );
insert into @UserProject ( UserId, UserProjectName, UserProjectNumber ) values
( 1, 'Beth', ( select IsNull( Max( UserProjectNumber ), 0 ) + 1 from @UserProject where UserId = 1 ) );
select *
from @UserProject
order by UserId, UserProjectNumber;
UserProjectNumber
当允许用户删除项目时,该列的维护就会出现问题。数字应该保持密集吗?新项目应该重用旧号码吗?
如果添加的目的UserProjectNumber
仅仅是为了显示,那么使用动态生成数字Row_Number() over ( partition by UserId order by UserProjectName )
或将其留给应用程序可能更有意义。
如果目的是强制每个用户限制六个项目,那么使用 的约束Count()
或触发器可能是更好的选择。