Is it possible to determine what caused a duplicate key values - sql-server

I have a job who makes replication between two databases and after I insert new value in first table tbl_company_market_service_phone_number I get this error from the job ,and the value not exists in table wich is replicated data (second table).
Error:Cannot insert duplicate key row in object 'tbl_company_market_service_phone_number' with
unique index 'IX_tbl_company_market_service_phone_number_fld_uk'. The duplicate key value is
(65b763ac-6f8f-4fe6-b76c-02a75b71dbe1).
How can I find what key value is (65b763ac-6f8f-4fe6-b76c-02a75b71dbe1) ? Or find out the cause of job faill.

So it is not in the replicated data
Did you check the source table
It is telling you table name tbl_company_market_service_phone_number
And that is the name of stated name of the source table

Related

How to do transaction.insert_or_update on secondary index and not the primary index?

I have a table in Google Cloud Spanner.
CREATE TABLE test_id (
Id STRING(MAX) NOT NULL,
KeyColumn STRING(MAX) NOT NULL,
parent_id INT64 NOT NULL,
Updated TIMESTAMP NOT NULL OPTIONS (allow_commit_timestamp=true),
) PRIMARY KEY (Id)
And, I am trying to perform transaction.insert_or_update through a python script.
For each row in a pandas dataframe, I am doing:
transaction.insert_or_update(
'test_id', columns=['Id','KeyColumn', 'parent_id', 'Updated'],
values=[(uuid.uuid4().hex, row["KeyColumn"], row["parent_id"], spanner.COMMIT_TIMESTAMP)],
)
What I want is that if the row["KeyColumn"] is already present in KeyColumn of the table, update its parent_id column, otherwise insert a new row in the Spanner table corresponding to that KeyColumn.
But since, my primary key is Id which is generated randomly by uuid.uuid4().hex, it every time inserts a new row.
If I understand you correctly, the following is the situation:
ID is the primary key of your table.
There is a unique index defined for the table on the column KeyColumn.
You want to insert_or_update a row using KeyColumn as the column that should be used to determine whether the row already exists.
That is unfortunately not possible. insert_or_update will always use the primary key of the table to determine whether the row exists. I can think of three possible solutions to this problem, but they all have their drawbacks:
You could change the table definition and make KeyColumn the primary key and set a unique index on the Id column. The problem with this is of course that any other code that depends on Id being the primary key also needs to change. It is also a rather cumbersome change, because Cloud Spanner does not allow you to change the primary key of a table, so you would have to create a copy of the test_id table and then drop the old table.
You could fetch the row from Cloud Spanner before updating it by reading it using the KeyColumn value that you have. The big problem with this is obviously performance. You will need to do a read for each row that you want to update.
You could use a DML statement (UPDATE test_id SET parent_id=#parent WHERE KeyColumn=#key) to execute the update and check whether it actually updated a row by checking the returned update count. If it did not update anything, you could then execute the insert. This will obviously also be slower than an insert_or_update mutation.
Here there is a way to query the Cloud Spanner with a specific index.
You should use something like this in the end of your query : FROM test_id#{FORCE_INDEX=KeyColumnIndex} .
Even though this is the way to execute queries on secondary indexes and the answer for the question in the title, I do not know how much it can be applied in your use case.

Duplicate Error when inserting unique non duplicate values T-SQL

Here is my other mistake I can't fight:
I am trying to add (INSERT INTO sql statement) a unique records from the WHID field
(ClientEpisode table) into WHID field (EHREpisode table):
INSERT INTO
[WH].[Fact].EHREpisode ([WHID])
SELECT
[HP].[bhcms5].ClientEpisode.WHID
FROM
[HP].[bhcms5].ClientEpisode
Both of the WHID fields are unique (non duplicated) in both tables, and between each others, but I keep having an error:
Plz, see the error message, in bigger letters:
"Cannot insert duplicate key row in object 'Fact.EHREpisode' with unique index 'IX_EHREpisode'. The duplicate key value is (NULL, NULL>).
The statement has been terminated."
Below are my tables structures:
EHREpisode:
ClientEpisode:
The error message seems to be saying something about NULL values being the culprit (your screen capture is hard to read). So, you may try excluding NULL values from being inserted:
INSERT INTO [WH].[Fact].EHREpisode ([WHID])
SELECT [HP].[bhcms5].ClientEpisode.WHID
FROM [HP].[bhcms5].ClientEpisode
WHERE [HP].[bhcms5].ClientEpisode.WHID IS NOT NULL;
As an alternative, consider using an index on WHID which ignores NULL values:
CREATE UNIQUE NONCLUSTERED INDEX idx_col1
ON [HP].[bhcms5].ClientEpisode (WHID)
WHERE WHID IS NOT NULL;
The error is very clear: There is a unique index called IX_EHREpisode with such columns that your query tries to insert the value (null,null) two times.
You have provided us a set of SSMS GUI pictures that are not really relevant to this. Instead, the way to use the GUI would be:
Go to the "Object explorer" at the left of SSMS
Find the table "EHREpisode" you are interested in
Open "Indexes". You should find IX_EHREpisode here. Open it.
Inside you will see the columns included in this index. There will be a couple of these that would both take NULL value if your query executed
Thus, you will either have to modify the index, or re-think your query.

Can one alter a PostgresSql table to have an autogenerated keys after the table has values?

Is it possible to only alter a table to make an existing column a serial auto generated key, without adding a new column? Sorry if this question is a bit newbie-ish for PostgreSQL, I'm more a SQL Server person but moving to PostgreSQL..
In a nut shell the program will copying an existing SQL Server database into PostgreSQL. With the desire to have a mirrored DB in PostgreSQL as the source from SQL Server with the only caveat one may selectively include/exclude any table or column as desired, or do everything...
Given the process copies all values, thought one should be able create the keys after the copy has finished just as one may do in SQL Server. Thought PostgreSQL would have a comparable methods as SQL Server's SET INSERT_IDENTITY [ON|OFF] so one may override the auto generated key with a desired value. Not seeing an equivalent in PostgreSQL. So my fallback is to create the mirrored records in Postgres without keys any keys and then alter the tables. But it seems to fix up the table as desired one has create a new column, but doing this break or cause a headache fixing up the RI for PK/FK relationships.
Any suggestions? Thanks in advance.
In PostgreSQL, the auto-generated key is always overridden if you insert an explicit value for it. If you don't specify a value (omit the column), or specify the keyword DEFAULT, a generated key is used.
Given table
CREATE TABLE t1 (id serial primary key, dat text);
then both these will get a generated key from sequence t1_id_seq:
INSERT INTO t1 (dat) VALUES ('fred');
INSERT INTO t1 (id, dat) VALUES (DEFAULT, 'bob');
This will instead provide its own value:
INSERT INTO t1 (id, dat) VALUES (42, 'joe');
You are responsible for ensuring that the provided value doesn't conflict with existing data, or with future values the identity sequence will generate. PostgreSQL will not notice that you manually inserted a row with id 42 and skip when its own sequence counter gets to that point.
Usually what you do is load with provided values, then reset the sequence to the max of all keys already in the table, so it keeps counting from there for new local inserts.

SSIS Error: Violation of primary key constraint. cannot insert duplicate key in object

I'm working with a team to resolve a SSIS package failure. The package contains four Sequence container and each container have some set of sql tasks which truncate a target table and insert data from a source to target. At times package fails with error: Violation of primary key constraint. cannot insert duplicate key in object even though there is no violation as the table is empty when we start the load. Please provide suggestions on how to troubleshoot the issue
Note: Source and destination have some difference in structure. Source tables containd PK on only one int column. Destination table contains one more additional PK which is a default value. I dont understand why we need a constrant on a default column value.
It sounds like even though the target table is empty when you run the SSIS package, the rows you're inserting themselves contain duplicate data. (i.e. if your PK is called [ID], you're trying to insert more than one of the same [ID] into the table)

SQL Server foreign key reference to 2 other primary keys

I have two tables:
Table1 with composite primary key - PRID, SPRID, STIM and
Table2 with primary key - MTID
I need the SPRID field to reference either PRID or MTID. I have seen examples where this can work if the value you want to put in SPRID is in both PRID and MTID but haven't yet seen any where it is only required to be in either. I have set cascade update and delete to ON and want this behavior for the finished design.
I have tried creating an intermediate table that is populated with PRID and MTID in a single field via triggers in both tables but it only seems to populate the MTID entries. When I try to enter data in Table 1 (in a view of Table1) I get the following message:
"This row was successfully committed to the database. However, a problem occurred when attempting to retrieve this record from the data back after the commit. ..."
When I re-query the record disappears. If I switch the FK constraint off I can enter data that complies with the constraints but as soon as I switch the constraint back on the data is deleted.
I can't change the db design as these tables are part of a commercial piece of software that I am trying to integrate with my SQL back end but am open to any suggestions of a suitable work around.
PRID and MTID are of nvarchar type (as is SPRID), both tables are in the same schema but you cannot have a PRID value that is the same as the MTID value.

Resources