簡體   English   中英

INSERT語句與外鍵沖突

[英]INSERT statement conflict with foreign key

我有2個表.'Member'和'ForgotPassword'表。 我面臨的問題是:

INSERT語句與FOREIGN KEY約束“ FK_ForgotPassword_User”沖突。 數據庫“ MyDatabase”的表“ dbo.Member”的列“ userID”中發生了沖突。

第一個表是“成員”表: userID是主鍵,我將其設置為自動遞增。

第二個表是“ ForgotPassword”表:我將userID設置為不是主鍵,而是將外鍵設置為對“ Member”表的引用,並將其設置為自動遞增。

我想要的是

要插入到ForgotPassword表中的Member表上的userID

當它運行第二條sql行時,你們所有人都知道出了什么問題?

using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Data;
    using System.Data.SqlClient;
    using System.Configuration;
    using System.Collections;



namespace DataAccessLayer
{
    public class Member3
    {
        string name;
        string email;
        string gender;
        string dateOfBirth;
        string nationality;
        string race;
        string address;
        string postalCode;
        string mobileNo;
        string password;
        string dateRegistered;
        string securityQuestion;
        string securityAnswer;

        public Member3(string name, string email, string gender, string dateOfBirth, string nationality, string race, string address, string postalCode, string mobileNo, string password, string dateRegistered, string securityQuestion, string securityAnswer)
        {
            this.name = name;
            this.email = email;
            this.gender = gender;
            this.dateOfBirth = dateOfBirth;
            this.nationality = nationality;
            this.race = race;
            this.address = address;
            this.postalCode = postalCode;
            this.mobileNo = mobileNo;
            this.password = password;
            this.dateRegistered = dateRegistered;
            this.securityQuestion = securityQuestion;
            this.securityAnswer = securityAnswer;
        }

        public string registerMember()
        {
            string status = "";
            string ConnString = Properties.Settings.Default.ConnectionString;

             string sql = "INSERT INTO Member (userName,Email,Gender,DateOfBirth,Nationality,Race,Address,PostalCode,MobileNumber,Password,DateRegistered) VALUES(@name, @email, @gender, @dateOfBirth, @nationality, @race, @address, @postalCode, @mobileNo, @password, @dateRegistered) SELECT IDENT_CURRENT('Member.userID) AS NewUser_ID";

            string sql2 = "INSERT INTO ForgotPassword (userID,SecurityQuestion, SecurityAnswer) VALUES(@NewUser_ID, @securityQuestion, @securityAnswer)";



                using (SqlConnection cn = new SqlConnection(ConnString))
                {

                    SqlCommand cmd;

                    cmd = new SqlCommand((sql), cn);

                    cmd.Parameters.AddWithValue("@name", name);
                    cmd.Parameters.AddWithValue("@email", email);
                    cmd.Parameters.AddWithValue("@gender", gender);
                    cmd.Parameters.AddWithValue("@dateOfBirth", dateOfBirth);
                    cmd.Parameters.AddWithValue("@nationality", nationality);
                    cmd.Parameters.AddWithValue("@race", race);
                    cmd.Parameters.AddWithValue("@address", address);
                    cmd.Parameters.AddWithValue("@postalCode", postalCode);
                    cmd.Parameters.AddWithValue("@mobileNo", mobileNo);
                    cmd.Parameters.AddWithValue("@password", password);
                    cmd.Parameters.AddWithValue("@dateRegistered", dateRegistered);





                    try
                    {
                        cn.Open();
                        cmd.ExecuteNonQuery();



                    }
                    catch (Exception ex)

                    {

                         status = ex.Message;
                         throw;

                    }



                        cmd = new SqlCommand(sql2,cn);
                        cmd.Parameters.AddWithValue("@securityQuestion", securityQuestion);
                        cmd.Parameters.AddWithValue("@securityAnswer", securityAnswer);

                   try
                    {
                        //cn.Open();
                        cmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                            status = ex.Message;
                            throw;
                    }

                    finally
                    {
                        cmd.Dispose();
                        status = "Member have been registered successfully!";

                    }
                }
                return status;

            }

        }
    }

您做錯了。請按照下列步驟操作。

  1. 您需要從成員表中將插入的鍵作為Ident_Current返回作為輸出參數。 這里
  2. 刪除忘記密碼表上的用戶ID自動遞增。
  3. 將步驟1中作為輸出參數返回的用戶ID插入ForgotPAssword表中

將SELECT SCOPE_IDENTITY()添加到查詢的末尾

string sql = "INSERT INTO Member   (userName,Email,Gender,DateOfBirth,Nationality,Race,Address,PostalCode,MobileNumber,Password,DateRegistered) VALUES(@name, @email, @gender, @dateOfBirth, @nationality, @race, @address, @postalCode, @mobileNo, @password, @dateRegistered) SELECT SCOPE_IDENTITY()"; 

然后使用獲取新ID

    int NewId= cmd.ExecuteScalar();

之后,將其作為參數傳遞給您的sql2查詢

替代@No,您可以在sp中完成整個操作,並使用必需的參數thats all調用該sp。 只是一個例子,不是實際的查詢。

Create proc MyProc
(@Param1 varchar(20), @Param2 varchar(20))
AS
BEGIN
Declare @Id as int  -- in case your PK is auto increment
Insert into Table1(B,C) Vaues(@Param1,@Param2)
Set @Id = @@Identity
Insert into Table2(FK_Table1,D)Values(@Id,@Param2) -- Here Id will be the FK , which you are 
                                         getting from the PK of the main table. 
END

現在,您的兩個表都已同步,並且不會出現任何此類錯誤。

在您的CS中再嵌入兩行

cmd.CommandText = "MyProc";
cmd.CommandType = CommandType.StoredProcedure // instead of .Text

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM