Check for duplicate values before letting user insert

I have an asp.net page that allows users to insert new records into a table. When they enter the data, I want to do a search of the empnum field to ensure that value does not exist already in the system. So before inserting, the page searches the users table for the empnum entered by the user. If it exits, show a message stating it already exists. If not, insert the record. What is the best way to do this? I'm using C# code behind.
dodgerfanAsked:
Who is Participating?
 
YZlatCommented:
string strConn="your connection string here";
string sql="SELECT COUNT(*) FROM Table1 WHERE ID=1";


using (SqlConnection conn = new SqlConnection(strConn))
{
	using (SqlCommand cmd = new SqlCommand(sql, conn))
        {
        	conn.Open();
                int count = (int)cmd.ExecuteScalar();
                if (count = 0)
                {
			using (SqlCommand cmdInsert = new SqlCommand("insert into Table1 (ID,Name) values (1,'test');", conn))
			{ 
				cmdInsert.ExecuteNonQuery(); 
			}
		}
         }

}

Open in new window

0
 
YZlatCommented:
string strConn="your connection string here";
string sql="SELECT COUNT(*) FROM Table1 WHERE ID=1";


using (SqlConnection conn = new SqlConnection(strConn))
                {

                    using (SqlCommand cmd = new SqlCommand(sql, conn))
                    {
                        conn.Open();
                        int count = (int)cmd.ExecuteScalar();
                        if (count> 0)
                            //record exists
                        else
                           //insert here
                    }

                }

Open in new window

0
 
dodgerfanAuthor Commented:
YZlat,
I'm grabbing the empum from a value entered into a textbox. The value can contain letters, so it's a string. Your code is erroring out on the line: int count = (int)cmd.ExecuteScalar(). It does not know what to do, I guess. Can I fix that?
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
YZlatCommented:
can you post your sql statement?
0
 
YZlatCommented:
your sql should be something like

sql="SELECT COUNT(*) FROM Table1 WHERE empnum='" + TextBox1.Text + "'";
0
 
YZlatCommented:
if the field in your where clause is of type text, you will need single quotes around the value

WHERE empnum = 'Test'
0
 
dodgerfanAuthor Commented:
Got it, thanks for the help. I just needed to get the syntax with those single and double quotes correct.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.