插入两个表,一个具有自动递增的主键,这是另一个的外键

时间:2016-07-17 22:23:13

标签: sql sql-server vb.net

我试图插入两个表格。第一个是我的产品表,其中主键是通过自动递增生成的,然后我想将该主键作为外键插入到我的product_ingredients表中。我该怎么做呢?

还要解释一下我目前正在尝试实现它,以便它只使用复选框提交在datagridview中选择的行

编辑:到目前为止我做了什么:

存储过程:

CREATE PROCEDURE Addproduct
@product_name            VARCHAR(50),
@product_category            VARCHAR(50),
@product_description            VARCHAR(MAX),
@price            money,
@product_stock            VARCHAR(50),
@new_identity    INT    OUTPUT
AS
BEGIN
    SET NOCOUNT ON

INSERT INTO product (product_name,product_category,product_description,price,product_stock)
VALUES (@product_name,@product_category,@product_description,@price,@product_stock)

SELECT @new_identity = SCOPE_IDENTITY()

SELECT @new_identity AS id

RETURN
END
GO

vb.net:

Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
        Dim emptyTextBoxes = From txt In Me.Controls.OfType(Of TextBox)()
                             Where String.IsNullOrEmpty(txt.Text) 'Ensures all fields are filled'
        If Not emptyTextBoxes.Any() Then
            Dim CMD As New SqlCommand("Addproduct", connection)
            CMD.Parameters("@Product_name", SqlDbType.VarChar).value = tbName.Text
            CMD.Parameters("@product_category", SqlDbType.VarChar).Direction = tbCategory.Text
            CMD.Parameters("@product_description", SqlDbType.VarChar).Direction = tbDescription.Text
            CMD.Parameters("@price", SqlDbType.Money).Direction = tbPrice.Text
            CMD.Parameters("@pproduct_stock", SqlDbType.VarChar).Direction = tbStock.Text

            CMD.Parameters("@New_Identity", SqlDbType.VarChar).Direction = ParameterDirection.ReturnValue

            CMD.CommandType = CommandType.StoredProcedure
            CMD.ExecuteNonQuery()
            Dim NewID = CMD.Parameters("@New_Identity").Value



        Else
            MsgBox("All fields must be filled")
        End If
    End Sub

2 个答案:

答案 0 :(得分:0)

这是一个常见问题。让您的插入例程返回SCOPE_IDENTITY()。

您应该查看参数化查询。它将使您的代码不易受SQL注入攻击。您还应该查看SqlHelper类

http://www.codeproject.com/Tips/555870/SQL-Helper-Class-Microsoft-NET-Utility

您使用的数据访问方法并不完全清楚。我猜这是你问题的一部分

我喜欢使用SqlHelper类来使用旧的ADO.NET。

' Add record to database   
    Dim id as Integer =  SqlHelper.ExecuteScalar(connection, "usp_product_ins", product_name, product_category, product_description)

以下是插入过程的示例:

enter code here
-- Insert stored prodedure.
CREATE PROCEDURE [dbo].[usp_product_ins] 
    @product_name varchar(32),
    @product_category int,
    @product_description varchar(255) 
AS
BEGIN
    Declare @result int = -1;

    INSERT INTO product (Product_Name, Product_Category, product_description)
    Values (@product_name, @product_category, @product_description)

    If (@@ROWCOUNT > 0) SET @result = SCOPE_IDENTITY();

    Select @result as Id;


END

您不必使用存储过程或SqlHelper类。 您可以使用内联sql(带参数)并包装您的值 作为SqlParameters(System.Data.SqlClient命名空间)并调用ExecuteScalar 直接

答案 1 :(得分:0)

这是StoredProcedure的解决方案。按照以下代码创建SP:

CREATE PROCEDURE InsertProcedureName
@product_name            VARCHAR(20),
@parameters2            VARCHAR(20), --define all parameters like this
@new_identity    INT    OUTPUT
AS
BEGIN
    SET NOCOUNT ON

INSERT INTO My_Table (product_name,TableCoumn2)
VALUES (@product_name,@parameter2)

SELECT @new_identity = SCOPE_IDENTITY()

SELECT @new_identity AS id

RETURN
END

从VB.Net调用存储过程

Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
    Dim emptyTextBoxes = From txt In Me.Controls.OfType(Of TextBox)()
                         Where String.IsNullOrEmpty(txt.Text) 'Ensures all fields are filled'
If Not emptyTextBoxes.Any() Then
   Dim CMD as new sqlCommand("InsertProcedureName",YourConnectionObject)       
   CMD.parameters("@product_name", sqlDBType.Int).value = tbName.Text
'repeat above line code for all the parameters defined in stored procedure
       CMD.parameters("@New_Identity",sqlDBType.Int).Direction = ParameterDirection.ReturnValue
   'Similarly for all parameters declared in stored procedure
   CMD.CommandType = CommandType.StoredProcedure
   CMD.ExecuteNonQuery()
   Dim NewID = CMD.Parameters("@New_Identity").Value

   'Use this NewID as foriegn key

Else
    MsgBox("All fields must be filled")
End If
End Sub

希望这会有所帮助并给你一个想法。感谢