日期:2014-05-18  浏览次数:20567 次

SQL写入数据问题~~ 请教各位~~ 急用~~
我刚学数据库   今天有个不会的问题请教一下各位  
比如插入表A中一条数据   表A中的一个ID项自动加1  
怎样在这个同时把加了1的这项ID的值   写入另一个表B?

麻烦大家告诉我语句怎么写~~   谢谢了!!

------解决方案--------------------
--建立測試環境
Create Table A(ID Int Identity(1,1), Name Varchar(10))
Create Table B(ID Int)
GO
--建立觸發器
Create Trigger Update_B On A
For Insert
As
Begin
Insert B Select ID From A
End
GO
--測試
Insert A Select 'A '
Union All Select 'B '

Select * From B
GO
--刪除測試環境
Drop Table A, B
--結果
/*
ID
1
2
*/

------解决方案--------------------
--建立測試環境
Create Table A(ID Int Identity(1,1), Name Varchar(10))
Create Table B(ID Int)
GO

create proc InsertTableA
(
@Name varchar(10)
)
as
begin tran

declare @ID int
insert into A(Name) select @Name
set @ID=@@Identity
if @@Error <> 0
goto Flag

insert into B(ID) select @ID
if @@Error <> 0
goto Flag

commit Tran
return

Flag:
rollback Tran
return
go

------解决方案--------------------
create table a (id int identity(1,1),name varchar(10))
create table b(id int)

create trigger inserttob on a
for insert
as
begin
insert into b select id from inserted
end

insert into a(name) select 'aaa '

select * from a


select * from b

id name
----------- ----------
1 aaa

(所影响的行数为 1 行)

id
-----------
1

(所影响的行数为 1 行)