张老师你好,请教你一个问题数据库方面的问题

[ 1816 查看 / 7 回复 ]

张老师你好,请教你一个数据库方面的问题,我把数据表设计好了,也用表关系设计好,但在程序中怎实现多表同时插入数据,比如说有个表是类别表,在另外一个表中添加详细信息,在程序中怎样实现这种插入。好好能给我一个例子。谢谢
最后编辑tygwy 最后编辑于 2010-04-13 10:29:17
TOP

这个估计最好用事务吧。。
TOP

还是请张老师指点一下
TOP

你好!典型做法是把参数传到存储过程中,在存储过程中使用事务,先插入主表,再插入从表.再使用输出参数输出操作结果,如是否成功.
TOP

张老师能传一个例子给我吗
TOP

/*
添加采购入库数据
1.插入主表
2.插入从表
3.更新最新进价、库存状态
4.更新导入状态
*/
ALTER Proc AddPurcaseInStoreRoom
@PurcaseInStoreRoomNo Char(30),
@InDate SmallDatetime,
@ProviderID Int,
@ArrivePurchaseInspectID Int,
@ArrivePurchaseInspectNo Char(30),
@Remark Varchar(100),
@TotalAmount Money,
@InputEmployeeID Int,
@AddDetailSql Varchar(500)
As
Declare @newId int, @State int, @tmpPid int, @tmpSid int, @tmpPrice money, @Pno Varchar(30), @Count int, @tmpstr Varchar(500)
Set @State = 0

Begin Tran
--插入主表
Insert Into tPurcaseInStoreRoom (PurcaseInStoreRoomNo, InDate, ProviderID, ArrivePurchaseInspectID, ArrivePurchaseInspectNo, Remark, IsSettled, TotalAmount, SettledAmount, RealPayAmount, InputEmployeeID, InputDateTime)
Values (@PurcaseInStoreRoomNo, @InDate, @ProviderID, @ArrivePurchaseInspectID, @ArrivePurchaseInspectNo, @Remark, 0, @TotalAmount, 0, 0, @InputEmployeeID, GetDate())

If @@Error <> 0
Begin
Rollback Tran
Return -1
End
Set @newId = @@Identity

--插入从表
Set @tmpstr = Convert(Varchar, @newId)
Set @tmpstr = Replace(@AddDetailSql, '-Id', @tmpstr)
Exec(@tmpstr)

If @@Error <> 0
Begin
Rollback Tran
Return -1
End

--更新商品最新进价以及库存状态
Declare Temp_Cursor Cursor
For
Select ProductID, StoreRoomID, Price, BatchNo, Amount From tPurcaseInStoreRoomDetail Where PurcaseInStoreRoomID = @newId

Open Temp_Cursor
--如果没有任何行则直接退出
If @@Cursor_Rows = 0
Begin
Close Temp_Cursor
Deallocate Temp_Cursor
End

While @State = 0
Begin
Fetch Temp_Cursor Into @tmpPid, @tmpSid, @tmpPrice, @Pno, @Count
Select @State = @@Fetch_Status

--修改最近进价
Update tProduct Set RecCostPrice = @tmpPrice Where ProductID = @tmpPid And RecCostPrice != @tmpPrice

--修改库存信息
--如果该批号商品存在于数据库中则更新
if (Exists(Select StoreRoomID From tStock Where ProductID = @tmpPid And BatchNo = @Pno))
Update tStock Set Amount = Amount + @Count Where ProductID = @tmpPid And BatchNo = @Pno
else
Insert Into tStock (StoreRoomID, ProductID, BatchNo, ProviderID, [ExpireDate], Amount, CostPrice, IsStopSale)
Values (@tmpSid, @tmpPid, @Pno, @ProviderID, GetDate(), @Count, @tmpPrice, 0)

If @@Error <> 0
Begin
Rollback Tran
Close Temp_Cursor
Deallocate Temp_Cursor
Return -1
End
End

Close Temp_Cursor
Deallocate Temp_Cursor

--修改导入状态
Update tArrivePurchaseInspect Set IsCite = 1 Where ArrivePurchaseInspectID = @ArrivePurchaseInspectID

If @@Error <> 0
Begin
Rollback Tran
Return -1
End
Commit Tran
Return @newId
TOP

太谢谢了张老师
TOP

太谢谢了
TOP