栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何创建由其他列细分的自动递增列

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何创建由其他列细分的自动递增列

CREATE TABLE dbo.MyTable (  myKey INT IDENTITY PRIMARY KEY,  category INT,  incrementalId INT);GOcreate table dbo.nextCategoryID (  category int,  nextidvalue int,  constraint PK_nextCategoryID primary key clustered( category, nextidvalue ));GOcreate trigger numberByCategory on dbo.MyTableafter insert as-- Automatically add any net new categoryinsert into dbo.nextCategoryID ( category, nextidvalue )    select distinct category, 1 as nextidvalue    from inserted    where not exists ( select * from dbo.nextCategoryID s        where s.category = inserted.category );-- Number the new rows in each incoming categorywith numberedrows as (    select         i.myKey,         i.category,         n.nextidvalue - 1 + row_number() over ( partition by i.category order by i.category ) as incrementalId    from inserted i    join dbo.nextCategoryID n on i.category = n.category)update m    set incrementalId = n.incrementalIdfrom dbo.MyTable mjoin inserted i on m.myKey = i.myKeyjoin numberedrows n on n.myKey = i.myKey;update dbo.nextCategoryID    set nextidvalue = 1 + ( select max( m.incrementalId )         from inserted i         join dbo.MyTable m on i.myKey = m.myKey        where i.category = nextCategoryID.category     )where exists ( select *     from inserted i    where i.category = nextCategoryID.category);GO-- Test dataINSERT INTO dbo.MyTable (category) VALUES (100);INSERT INTO dbo.MyTable (category) VALUES (200);INSERT INTO dbo.MyTable (category) VALUES (100);INSERT INTO dbo.MyTable (category) VALUES (100);INSERT INTO dbo.MyTable (category) VALUES (100);INSERT INTO dbo.MyTable (category) VALUES (200);insert into dbo.MyTable (category) values     ( 200 ),    ( 200 ),    ( 100 ),    ( 300 ),    ( 400 ),    ( 400 )SELECt *FROM dbo.MyTable;


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/414791.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号