且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将值插入2个表(外键)同时使用Visual Basic

更新时间:2023-01-29 08:54:57

最简单的方法是使用存储过程进行第一次插入,返回新客户记录的ID。



存储过程:

The easiest way to do this is to do the first insert with a stored procedure, returning the ID of the new customer record.

Stored proc:
CREATE PROCEDURE prc_AddCustomer 
	@Company NVARCHAR (50),
	@ContactName NVARCHAR (50),
	@Phone NVARCHAR (50)

AS
BEGIN
INSERT INTO Customers(Company, ContactName, Phone)VALUES(Company, @ContactName, @Phone)

RETURN @@IDENTITY

END
GO





调用程序(注意参数化查询以避免SQL注入):



Call the procedure (note parameterize query to avoid SQL Injection):

Dim Cmd As New SqlCommand("prc_AddCustomer", MyConn)
Dim lID as Long = 0

...
Cmd.CommandType = Data.CommandType.StoredProcedure
Cmd.Parameters.AddWithValue("@Company", txtCompany.Text)
Cmd.Parameters.AddWithValue("@ContactName", txtContactName.Text)
Cmd.Parameters.AddWithValue("@Phone", txtPhone.Text)
Cmd.Parameters.Add( _
        New SqlParameter("@ReturnValue", _
        Data.SqlDbType.Int))
Cmd.Parameters.Item("@ReturnValue").Direction = _
         Data.ParameterDirection.ReturnValue
MyConn.Open()
Cmd.ExecuteNonQuery()
lID=CInt(Cmd.Parameters.Item("@ReturnValue").Value)



您现在可以使用lID中返回的ID。



注意:

您可以同时插入存储的一个程序,但这可能会降低可重用性。

使用Try / Catch块始终围绕数据库访问。


You can now use the returned ID that's in "lID".

Notes:
You could do both insert in the one stored procedure, but this might reduce the reusability.
Always surround your DB access with a Try/Catch block.


用于插入Orders表的SQL语句不使用CustomersID作为值。您是否认为SQL Server会以某种方式神奇地知道此订单应该是哪个客户?为了防止在没有有效外键引用的情况下创建Orders,该字段不允许NULL值。



干杯!
Your SQL statement for inserting into the Orders table doesn't use the CustomersID as a value. Do you think SQL Server would somehow magically know for which customer this Order should be? To prevent creating Orders without a valid foreign key reference to Customers that field should not allow NULL values.

Cheers!