Showing posts with label random. Show all posts
Showing posts with label random. Show all posts

Thursday, March 8, 2012

Check before INSERT

I have a pretty standard form that inserts users name, office, and team. It generates a random 10 digit ID for them. How would i got about checking the table to make sure that ID doesn't exist?

Here's my insert code.

string strConnection = ConfigurationManager.ConnectionStrings["TimeAccountingConnectionString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(strConnection);

string usercode = GenPassWithCap(9);

String insertCmd = "INSERT into users (ID, firstname, lastname, office, team) values (@.id, @.firstname, @.lastname, @.office, @.team)";
SqlCommand myCommand = new SqlCommand(insertCmd, myConnection);

myCommand.Parameters.Add(new SqlParameter("@.id", SqlDbType.VarChar, 10));
myCommand.Parameters["@.id"].Value = usercode;

myCommand.Parameters.Add(new SqlParameter("@.firstname", SqlDbType.VarChar, 50));
myCommand.Parameters["@.firstname"].Value = txtFirstName.Text;

myCommand.Parameters.Add(new SqlParameter("@.lastname", SqlDbType.VarChar, 50));
myCommand.Parameters["@.lastname"].Value = txtLastName.Text;

myCommand.Parameters.Add(new SqlParameter("@.office", SqlDbType.VarChar, 75));
myCommand.Parameters["@.office"].Value = dwnOffice.SelectedValue;

myCommand.Parameters.Add(new SqlParameter("@.team", SqlDbType.VarChar, 20));
myCommand.Parameters["@.team"].Value = dwnTeam.SelectedValue;

myCommand.Connection.Open();

myCommand.ExecuteNonQuery();

Do I run a completey different select command before hand and try to match that field?

Instead of an adhoc T-SQL like this, you could pass the parameters to a proc and do a check before inserting.

IF NOT EXISTS(SELECT * FROM TableWHERE Id = @.ID AND Lastname = @.LastName And...)

INSERT INTO Users (...)