我有一个带有字段的表:UserProjectNumber,这只是一个每次需要递增1的int字段。我目前使用以下INSERT语句递增此数字。只要表中已有该用户的记录,这就完美无缺。如果这是第一次运行语句,则会失败,因为它无法将1添加到NULL
INSERT INTO UserProject (UserID, UserProjectName, UserProjectNumber)
VALUES (2, 'Test', CASE WHEN (SELECT MAX(UserProjectNumber) FROM UserProject WHERE UserID=2)= NULL THEN 0 ELSE (SELECT MAX(UserProjectNumber) FROM UserProject WHERE UserID=2)+1 END )
我正在使用MS SQL Server 2012.任何人都可以提出解决此问题的方法吗?也许以某种方式将NULL转换为0?
由于
答案 0 :(得分:1)
也许会这样:
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()
或触发器的约束可能是更好的选择。
答案 1 :(得分:0)
INSERT INTO UserProject (UserID, UserProjectName, UserProjectNumber)
VALUES (2, 'Test', ISNULL((SELECT MAX(UserProjectNumber) FROM UserProject WHERE UserID=2),0)+1)