Sunday, February 19, 2012

How to know if a record exists

Hello,

I have a TextBox and an Insert Button, it works like this:

protected void Button1_Click(object sender, EventArgs e)
{
String strConn=SqlDataSource1.ConnectionString;
SqlCommand cmd =new SqlCommand("INSERT INTO My_Table_1 (Column_1) VALUES ("+TextBox1.Text+")",new SqlConnection(strConn));

cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}


But,what code i must write for checking, if the value i am trying to insert already exists ??

I mean something like this:

if (TextBox1.Text does not Exists on any Record in My_Table_1) then
Insert it
else
Show Message : "Already exists a record with this value"

Thank you SO MUCH, guys,

Carlos.you can execute "select count(*) from My_Table_1 whereColumn_1='"+TextBox1.Text+"'" before insert and get value of the firstcolumn, then use if to determine whether it is bigger than 0|||

you could write a stored procedure and pass the insert parameters to it. In the stored proc you could do a check as follows:

IF NOT EXISTS(SELECT * FROM <table> WHERE <Condition>)

BEGIN

INSERT INTO <table> (<columns>) VALUES (<Values>)

END

If you want to return an appropriate message back to the front end you could include a return value as an OUTPUT parameter and return a code appropriately.

|||Hello Tony and Ndinakar:

thanks for the replies ;)

I will try first Tony's method...

BUT, how can i get the value of the first column ?

Please, can you write some code? i am REALLY new on this, and i can't find the answer :(

Thank you so much,

Carlos.|||code sample for you:)

//open connection
SqlConnection m_conn=new SqlConnection(ConnectionString);
m_conn.Open();
//run sql
sqlstring="select count(*) from My_Table_1 whereColumn_1='"+TextBox1.Text+"'" ";
SqlCommand sqlcmd=new SqlCommand(sqlstring,m_Conn);
SqlDataReader sdr=sqlcmd.ExecuteReader();
sdr.Read();
int rowcount=(int)sdr[0]; //here, you get what you need!
sdr.Close();
//determine whether record exist
if(rowcount==0)
{
//insert a new record
}
//close you connection
m_conn.Close();|||With all due respect... The second solution will give you better performance. It is essentiall the same as the first, except the exists contraint tells the query to stop executing after it finds a single match, whereas the count(*) method continues to aggregate the entire selection.|||Yes, you will be making 2 trips to insert a record which is unnecessary.|||Thank you guys for all your replies.

Tony, your code works 100% for what i am looking for, thank you ;)

In a few days i will study stored procedures, and i will try the second solution, and i will post my results here.

Thanks again,

Carlos.

No comments:

Post a Comment