2016-10-27 98 views
0

我正在使用C#編寫一個asp.net頁面。我有一個包含3列(FirstName,CLNum,LastName)的表。我正在嘗試使用簡單的SQL查詢來防止用戶在CLNum中輸入重複數據。這是我試過......ASP.net中的SQL WHERE子句錯誤

INSERT INTO tblClock ([FirstName],[CL],[LastName]) VALUES (@FirstName, @CL, @LastName) WHERE @CL NOT IN (SELECT CL FROM tblClock) 

頁面編譯罰款,但後來當我試圖提交的數據,我得到這個錯誤:

不正確的語法關鍵字「WHERE」附近。 描述:執行當前Web請求期間發生未處理的異常。請查看堆棧跟蹤以獲取有關該錯誤的更多信息以及源代碼的位置。

異常詳細信息:System.Data.SqlClient.SqlException:關鍵字'WHERE'附近的語法不正確。

源錯誤:

67行:cmd.Connection = sqlCon;

第68行:sqlCon.Open();

第69行:IsAdded = cmd.ExecuteNonQuery()> 0;

70行:sqlCon.Close();

行71:}

下面是一段代碼我工作:

//Insert click event to insert new record to database 
    protected void btnInsert_Click(object sender, EventArgs e) 
    { 
     bool IsAdded = false; 
     string FirstName = txtFirstName.Text.Trim(); 
     int CL = Convert.ToInt32(txtCL.Text); 
     string LastName = txtLastName.Text; 
     using (SqlConnection sqlCon = new SqlConnection(conn)) 
     { 
      using (SqlCommand cmd = new SqlCommand()) 
      { 
       cmd.CommandText = "INSERT INTO tblClock ([FirstName],[CL],[LastName]) VALUES (@FirstName, @CL, @LastName) WHERE @CL NOT IN (SELECT CL FROM tblClock)"; 
       cmd.Parameters.AddWithValue("@FirstName", FirstName); 
       cmd.Parameters.AddWithValue("@CL", CL); 
       cmd.Parameters.AddWithValue("@LastName", LastName); 
       cmd.Connection = sqlCon; 
       sqlCon.Open(); 
       IsAdded = cmd.ExecuteNonQuery() > 0; 
       sqlCon.Close(); 
      } 
     } 
     if (IsAdded) 
     { 
      lblMsg.Text = "'" + FirstName + " " + LastName + "' has been successfully added!"; 
      lblMsg.ForeColor = System.Drawing.Color.Green; 

      BindSubjectData(); 
     } 
     else 
     { 
      lblMsg.Text = "Error while adding '" + FirstName + " " + LastName + "' subject details"; 
      lblMsg.ForeColor = System.Drawing.Color.Red; 
     } 
     ResetAll();//to reset all form controls 
    } 

任何想法?

+0

可能的複製http://stackoverflow.com/questions/913841/mysql-conditional-insert的 – TheFallenOne

回答

0

嘗試這種方式

INSERT INTO tblClock 
      ([FirstName],[CL],[LastName]) 
SELECT @FirstName, 
     @CL, 
     @LastName 
WHERE NOT EXISTS (SELECT 1 
        FROM tblClock 
        WHERE CL = @CL) 
+0

謝謝,Prdp!這工作! –