C# .Net3.5 adding data to a SQL Server 2005 database if it dosn't already exist and if it does update it?
Hi now playing with SQL for the first time!
I have the code below which works fine but I need to check if the entry is already in the database using CustomerName and Product to match on and if it is in the database update the other fields and if not insert all the data.
How would I do this?
Below is the code I use to insert a new record:
DateTime FirstDateSeen = new DateTime();
FirstDateSeen = DateTime.Now.Date;
DateTime LastDateSeen = new DateTime();
LastDateSeen = DateTime.Now.Date;
SqlConnectionStringBuilder MySqlConnection = new SqlConnectionStringBuilder("MY CONNECTION");
SqlConnection db = new SqlConnection(MySqlConnection.ToString());
try //sql string for first seen
{
string sqlIns = "INSERT INTO Customer (Product, Version, CustomerName, CustomerPostcode, FirstSeen, LastSeen)" +
"VALUES (@Product, @Version, @CustomerName, @CustomerPostcode, @FirstSeen, @LastSeen)";
db.Open();
SqlCommand cmdIns = new SqlCommand(sqlIns, db);
cmdIns.Parameters.Add("@CustomerName", UniqueA);
cmdIns.Parameters.Add("@Product", AppName);
cmdIns.Parameters.Add("@Version", AppVer);
cmdIns.Parameters.Add("@CustomerPostcode", UniqueB);
cmdIns.Parameters.Add("@FirstSeen", FirstDateSeen.ToShortDateString());
cmdIns.Parameters.Add("@LastSeen", LastDateSeen.ToShortDateString());
cmdIns.ExecuteNonQuery();
cmdIns.Parameters.Clear();
cmdIns.Dis开发者_运维问答pose();
cmdIns = null;
}
catch (Exception ex)
{
throw new Exception(ex.ToString(), ex);
}
finally
{
db.Close();
}
Are you married to SQL 2005? If not I would suggest looking at SQL 2008 as it addresses this with the MERGE command. If you are in a situation that you can't use SQL 2008 then its a simple matter of wrapping these commands in a bit more SQL code.
IF EXISTS (<Preform your Check>)
BEGIN
Update ... blah blah
END
ELSE
BEGIN
INSERT ()...
END
IF EXISTS(SELECT CustomerName FROM Customer WHERE CustomerName = @CustomerName)
BEGIN
UPDATE Customer ..
END
ELSE
BEGIN
INSERT INTO Customer (Product, Version, CustomerName, CustomerPostcode, FirstSeen, LastSeen)
VALUES (@Product, @Version, @CustomerName, @CustomerPostcode, @FirstSeen, @LastSeen)
END
Lots of other fun stuff going on here...
Here is one pointer
catch (Exception ex)
{
throw new Exception(ex.ToString(), ex);
}
is better as
catch (Exception ex)
{
// do stuff
throw;
}
or
catch ()
{
throw;
}
instead of writing your sql query on your code, you can create a procedure for that and write that. and in the procedure using if else, you can check if there is an entry or not, if there is you write your update query with your parameters, else you write your insert query.
First execute a query like that:
SELECT COUNT(*) AS RecordCount FROM Customer
WHERE Product=@Product AND CustomerName=@CustomerName
If RecordCount
is 0, make the insert, if not make an update.
精彩评论