Sql update: continue updating after duplicate key error (transact-SQL) - sql-update

I have the following script:
update myTable set FieldValue = 1 where FieldValue = 2
Now lets assume that I have 10 entries in mytable and when updating the 5th element, I get the duplicate key insertion error:
Cannot insert duplicate key row in object 'dbo.mytable'
with unique index. The
duplicate key value is (FieldValue).
and the updating of the elements which had to be updated after the 5th one is not done.
It would be ok for me to do nothing if the error occurs and to step over the updating of the element which cannot be updated because of getting the error above.
How can I continue the updating of the rest of the elements after this kind of error?

Use the IGNORE keyword like so:
update IGNORE myTable set FieldValue = 1 where FieldValue = 2;
If a record update fails (e.g. because of a unique key contraint), it will be skipped and the others will continue.

Related

find a row from DynamoDB w/o hash and range key and delete it

Is there a way to remove a record/row from DynamoDB without using the hash key and range key?
Here is my table look like:
I have a value of instance_id and based on that I would delete the row but getting errors:
here is the code I am using:
table.delete_item(
Key={
'instance_id':'i-0b2b314a'
}
)
The delete_item() documentation says:
Deletes a single item in a table by primary key.
So, it is not possible to delete by a value that is not the primary key.
You would need to scan (expensive in terms of RCUs!) for the rows with that value, then delete the returned items.

AWS DynamoDB query with Key Condition Expression got an error: Query key condition not supported

The image below show my table's structure
And try to querying the list of item with Java code below:
QuerySpec qs = new QuerySpec()
.withKeyConditionExpression("RecordID >= :v_recordID")
.withFilterExpression("DeviceID = :v_deviceID")
.withValueMap(new ValueMap()
.withInt(":v_recordID", recordID)
.withString(":v_deviceID", deviceID)
);
I wanna to get items with RecordID greater than or equal 5, but it got an error:
Query key condition not supported
How to solve it, thanks in advance !
Check out link : http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Query.html
The partition key equality test is required, and must be specified in the following format:
partitionKeyName = :partitionkeyval

How to get after executing INSERT into database fetch id of inserted row?

I am using c++11 and pqxx to access postgresql database and I need id of inserted row and flag if it was successful or not.
How to get after executing INSERT into database fetch id of inserted row ?
I have tried to find example on net but without success.
work txn(*conn);
txn.prepared("insert ")(person_name).exec();
txn.commit();
work txn(*conn);
pqxx::result r = txn.prepared("insert into t (a,b,c) values (1,2,$1) returning id")(person_name).exec();
txn.commit();
int id = r[0][0].as<int>();

sql Column with multiple values (query implementation in a cpp file )

I am using this link.
I have connected my cpp file with Eclipse to my Database with 3 tables (two simple tables
Person and Item
and a third one PersonItem that connects them). In the third table I use one simple primary and then two foreign keys like that:
CREATE TABLE PersonsItems(PersonsItemsId int not null auto_increment primary key,
Person_Id int not null,
Item_id int not null,
constraint fk_Person_id foreign key (Person_Id) references Person(PersonId),
constraint fk_Item_id foreign key (Item_id) references Items(ItemId));
So, then with embedded sql in c I want a Person to have multiple items.
My code:
mysql_query(connection, \
"INSERT INTO PersonsItems(PersonsItemsId, Person_Id, Item_id) VALUES (1,1,5), (1,1,8);");
printf("%ld PersonsItems Row(s) Updated!\n", (long) mysql_affected_rows(connection));
//SELECT newly inserted record.
mysql_query(connection, \
"SELECT Order_id FROM PersonsItems");
//Resource struct with rows of returned data.
resource = mysql_use_result(connection);
// Fetch multiple results
while((result = mysql_fetch_row(resource))) {
printf("%s %s\n",result[0], result[1]);
}
My result is
-1 PersonsItems Row(s) Updated!
5
but with VALUES (1,1,5), (1,1,8);
I would like that to be
-1 PersonsItems Row(s) Updated!
5 8
Can somone tell me why is this not happening?
Kind regards.
I suspect this is because your first insert is failing with the following error:
Duplicate entry '1' for key 'PRIMARY'
Because you are trying to insert 1 twice into the PersonsItemsId which is the primary key so has to be unique (it is also auto_increment so there is no need to specify a value at all);
This is why rows affected is -1, and why in this line:
printf("%s %s\n",result[0], result[1]);
you are only seeing 5 because the first statement failed after the values (1,1,5) had already been inserted, so there is still one row of data in the table.
I think to get the behaviour you are expecting you need to use the ON DUPLICATE KEY UPDATE syntax:
INSERT INTO PersonsItems(PersonsItemsId, Person_Id, order_id)
VALUES (1,1,5), (1,1,8)
ON DUPLICATE KEY UPDATE Person_id = VALUES(person_Id), Order_ID = VALUES(Order_ID);
Example on SQL Fiddle
Or do not specify the value for personsItemsID and let auto_increment do its thing:
INSERT INTO PersonsItems( Person_Id, order_id)
VALUES (1,5), (1,8);
Example on SQL Fiddle
I think you have a typo or mistake in your two queries.
You are inserting "PersonsItemsId, Person_Id, Item_id"
INSERT INTO PersonsItems(PersonsItemsId, Person_Id, Item_id) VALUES (1,1,5), (1,1,8)
and then your select statement selects "Order_id".
SELECT Order_id FROM PersonsItems
In order to achieve 5, 8 as you request, your second query needs to be:
SELECT Item_id FROM PersonsItems
Edit to add:
Your primary key is autoincrement so you don't need to pass it to your insert statement (in fact it will error as you pass 1 twice).
You only need to insert your other columns:
INSERT INTO PersonsItems(Person_Id, Item_id) VALUES (1,5), (1,8)

How to catch Unique constraint error in POSTGRESQL

If I create a table with a unique contraint, for example:
CREATE TABLE distributors (
did integer,
name varchar(40) UNIQUE
);
What would happen if I try to enter an entry with the name that already exists. I tried to do so and it just quit without displaying any error message. Is there a way to check whether a new entry was actually inserted?
If the insert failed than there should be error code set somewhere, readable by some method of the interface you're using - more details are definitely in documentation to your access library/module.
Alternatively you can change your insert to:
INSERT INTO distributors (did, name) values ( ... ) RETURNING did;
And if it didn't return anything - there has been error.
If you try to insert record with name that already exists, you'll receive error message like this:
ERROR: duplicate key value violates unique constraint "distributors_name_key"
DETAIL: Key (name)=(aaa) already exists.
and record will not be inserted.
If you do it from allplcation level, the exception will be thrown with a message similar to this. It's up to the programmer how to handle this exception.
If your ID field is autogenerating (SERIAL or BIGSERIAL), and you insert just name, if you insert name which already exists, ID sequence will increase by 1, even if you didn't insert any record.
To avoid that you can make "SELECT" query before INSERT to check, it the record already exists. Possible to do all in one transaction, in pseudo-code:
BEGIN TRANSACTION;
int records = SELECT name FROM table WHERE name = 'aaa' FOR UPDATE; //FOR UPDATE to lock the row from being read by other user until transaction finishes.
if (records == 0)
INSERT INTO table VALUES (1, 'aaa');
else
MessageBox.Show("Record already exists");
COMMIT TRANSACCTION;