How can I INSERT
a row if does not yet exist in a SQL Server CE database table and UPDATE
it if it exists?
I have tried lot of SQL queries and keep getting errors. This is not working.
IF EXISTS (SELECT * FROM Table1 WHERE Column1='SomeValue')
UPDATE Table1 SET (...) WHERE Column1='SomeValue'
ELSE
INSERT INTO Table1 VALUES (...)
Update:
I have found this which is working for me. Any other good suggestion is welcome.
INSERT INTO Table1 VALUES (...)
SELECT (........)
WHERE NOT Exists (SELECT ........)
-- INSERT with Default value if not exist. Next, UPDATE it
UPDATE Table1 SET (...) WHERE Column1='SomeValue'
The INSERT OR UPDATE command is an extension of the INSERT command, with these differences: If the row being inserted does not exist, INSERT OR UPDATE performs an INSERT operation. If the row being inserted already exists, INSERT OR UPDATE performs an UPDATE operation, updating the row with the specified column values.
An alternative for IN and EXISTS is an INNER JOIN, while a LEFT OUTER JOIN with a WHERE clause checking for NULL values can be used as an alternative for NOT IN and NOT EXISTS.
I know you've tagged sql and sql-server-ce but in case you're open to using c# code to fix this.. :
Using c# and result sets this is what I did for my mobile app using SQL CE:
// UpdateRow is a struct/class to hold the data for each row
// SqlCeConn = connection string for db
SqlCeCommand cmd = new SqlCeCommand("Table1", SqlCeConn);
cmd.CommandType = CommandType.TableDirect;
cmd.IndexName = "Column1";
using (SqlCeResultSet rsltSet = cmd.ExecuteResultSet(ResultSetOptions.Scrollable | ResultSetOptions.Updatable))
{
if (UpdateRow.Column1> 0) // or != "" if it's string etc
{
if (rsltSet.Seek(DbSeekOptions.FirstEqual, UpdateRow.Column1))
FoundRecord = true;
}
rsltSet.Read();
if (FoundRecord)
{
// Update
rsltSet.SetInt32(1, UpdateRow.Column1);
rsltSet.SetInt32(2, UpdateRow.Column2);
// etc
rsltSet.Update();
}
else
{
// Insert new record
SqlCeUpdatableRecord record = rsltSet.CreateRecord();
record.SetInt32(0, UpdateRow.Column1);
record.SetInt32(1, UpdateRow.Column2);
// etc
rsltSet.Insert(record, DbInsertOptions.PositionOnInsertedRow);
}
}
cmd.Dispose();
}
catch (Exception e)
{
// Deal with exception
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With