这种插入语句要怎么写

小野马1209 2020-03-24 10:05:58
--需求描述:将T1表数据插入T2表,插入条件是 表2的FromRowId不在表1中
--要求表2的RowId能从表2最大的RowId开始编号(表2的RowId和BillNo是主合键)
CREATE TABLE T1(BillNo VARCHAR(100),RowId int,FromRowId int primary key(BillNo,RowId))--【单据编号】【标识号】【来源标识号】
INSERT INTO T1
SELECT 'No1',1,5UNION ALL
SELECT 'No1',2,13UNION ALL
SELECT 'No1',6,22 UNION ALL
SELECT 'No1',7,33

CREATE TABLE T2(BillNo VARCHAR(100),RowId int,FromRowId int primary key(BillNo,RowId))--【单据编号】【标识号】【来源标识号】
INSERT INTO T2
SELECT 'No2',8,5 UNION ALL
SELECT 'No2',9,13



--插入后查询表2想要的结果(RowId 按当前最大数+1)
BillNo RowId FromRowId
No2 8 5
No2 9 13
No2 10 22
No2 11 33


...全文
106 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
Hello World, 2020-03-24
  • 打赏
  • 举报
回复


;with t as (select fromrowid,(select max(rowid) from t2) maxid,
row_number() over (order by fromrowid) seq
from t1 a
where not exists (select 1 from t2 b where a.fromrowid = b.fromrowid))
select fromrowid,maxid+seq as rowid into #temp from t

insert into t2(billno,rowid,fromrowid) select 'No2',rowid,fromrowid from #temp

select * from t2

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧