当前位置: 代码迷 >> Sql Server >> [贴] 关于一条SQL添加到两个不同的表
  详细解决方案

[贴] 关于一条SQL添加到两个不同的表

热度:505   发布时间:2016-04-27 14:37:51.0
[求助贴] 关于一条SQL添加到两个不同的表

表结构.

table1
StuId,BodyID,Gender,Name,...10多个字段
table2
StuId,Pwd,Name 3个字段


我现在想用一条SQL,同时把一条数据添加到这两个数据表中.

只有两个要求.

1、table2 的 StuID=table1.StuId(同时添加的)
2、Name 的 Name = table1.Name(也是同时添加)

我写的 SQL:

SQL code
declare @Name nvarchar(50) ='aclie',            @Birthday nvarchar(50) ='2011-1-1',            @StaData nvarchar(50) = '2011-1-1',            @Gender nvarchar(50) ='男',            @Nation nvarchar(50)='维吾尔族',            @BodyID nvarchar(50)='123456789123456789'insert into Stu_info (Name,Birthday,StaData,Gender,Nation,BodyID) values (@Name,@Birthday,@StaData,@Gender,@BodyID) ;insert into StuAcct (SName,SPwd,StuId) select StuID,Name,RIGHT(BodyID,6)  StuAcct from Stu_info where [email protected]


我想用 select into 同时去添加,但是最后发现还是不行.

我知道这个语句肯定是有错的,求大牛给点思路.

------解决方案--------------------

------解决方案--------------------
用output
------解决方案--------------------
SQL code
触发器
------解决方案--------------------
这个可以做个判断
如果条件符合同时添加
------解决方案--------------------
declare @Name nvarchar(50)
 declare @Birthday nvarchar(50)
 declare @StaData nvarchar(50) 
declare @Gender nvarchar(50) 
declare @Nation nvarchar(50
declare @BodyID nvarchar(50
set @Name ='aclie'
set @Birthday ='2011-1-1'
set @StaData = '2011-1-1'
set @Gender ='男'
set @Nation ='维吾尔族'
set @BodyID ='123456789123456789'


insert into Stu_info (Name,Birthday,StaData,Gender,Nation,BodyID) values (@Name,@Birthday,@StaData,@Gender,@Nation,@BodyID) ;
insert into StuAcct (SName,SPwd,StuId) select StuID,Name,RIGHT(BodyID,6) from Stu_info where [email protected]
 
 
------解决方案--------------------
呼叫水哥
------解决方案--------------------
是不是写个事务处理,tabel1 insert成功了然后提取第一个的信息添加进tabel2
------解决方案--------------------
探讨
用output

------解决方案--------------------
CREATE TRIGGER [dbo].[test_INSERT] ON [dbo].[table1]
FOR INSERT
AS
BEGIN

declare @StuID as nvarchar(50)
declare @Name as nvarchar(50)

set @StuID = (select StuID from inserted )
set @Name = (select Name from inserted)

Insert into table2(StuID, Name ) Values(@StuID,@Name)

END


GO
------解决方案--------------------
SQL code
create table tb1 (    id    int identity(1,1),    name    varchar(10))create table tb2(    id    int ,    name    varchar(10))declare @name nvarchar(10);set @name = 'aaa';insert into tb1 values(@name)insert into tb2 select * from tb1 where name = @nameselect * from tb1 select * from tb2/*id,name1,aaa(1 行受影响)id,name1,aaa(1 行受影响)
------解决方案--------------------
再加一个条件
SQL code
insert into tb2 select * from tb1 where name = @name and id = @@identity
------解决方案--------------------
  相关解决方案