sqlserver插入数据到一个业务表,分拆到两个表中,用一个关联id关联

qq_24613633 2018-03-14 09:01:12
假设有三个表A,B,C,当往A中插入一条数据时自动分拆到B,C中,且生成相关联的ID,第一种方法ID由guid产生。因为环境是2008还没有sequence,所以再考虑一种替代sequence的方法,使得产生ID。初学sql,真的愁死了,有没有大佬能帮忙。
...全文
970 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
zjcxc 2018-03-15
  • 打赏
  • 举报
回复
示例
create table a(
	id int identity primary key,	-- 自增列,自动生成 id
	to_b int,	-- 该列连同 id 分拆到 b 表
	to_c int	-- 该列连同 id 分拆到 c 表
);
create table b(
	a_id int primary key,
	b int
);
create table c(
	a_id int primary key,
	c int
);
go

-- 自动拆分 的触发器
create trigger tr_insert on a after insert
as
insert b(a_id, b) select id, to_b from inserted;
insert c(a_id, c) select id, to_c from inserted;
go

-- 测试
insert a( to_b, to_c ) values(11,22);
insert a( to_b, to_c ) values(111,221), (333, 444);
select * from a;
select * from b;
select * from c;
go

drop table a,b,c
二月十六 2018-03-15
  • 打赏
  • 举报
回复
如果对ID没什么特殊要求,直接用自增长就行,如果有要求,比如时间+增长的数字,可以试试这种形式
if object_id('ta')is not null drop table ta

create table ta(id int identity(1000,1),vb AS CONVERT(NVARCHAR(100),GETDATE(),112)+RTRIM(id),vc int)

INSERT INTO ta(vc)VALUES(1)

SELECT * FROM ta




拆分问题,用存储过程或触发器都可以实现
  • 打赏
  • 举报
回复 1
if object_id('ta')is not null drop table ta
if object_id('tb')is not null drop table tb
if object_id('tc')is not null drop table tc

create table ta(id int identity(1000,1),vb int,vc int)
create table tb(id int ,vb int)
create table tc(id int ,vc int)

declare @t table(id int,vb int,vc int)
insert ta(vb,vc) output inserted.* into @t select 10,20 union all select 20,50

insert tb select id,vb from @t
insert tc select id,vc from @t

select * from ta
select * from tb
select * from tc

/* ta
id	vb	vc
1000	10	20
1001	20	50

tb
id	vb
1000	10
1001	20

tc
id	vc
1000	20
1001	50

27,579

社区成员

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

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