Incorrect Duplicate insert problem with SQL Server CE 3.5 - winforms

I am not able to insert data into my table anymore!
Here's my table design.
intId is the Primary Key, there's no explicit unique constraint defined on it, has identity increment set to 1 and identity seed to 1.
I am inserting data into this table thru LINQ.
testDB.tbl_Vehicle.InsertOnSubmit(newVehicle);
testDB.SubmitChanges();
All this used to work till now, and all of a sudden it stopped working!
It now says
A duplicate value cannot be inserted into a unique index. [ Table name = tbl_Vehicle,Constraint name = PK_tbl_Vehicle ]
More info: This desktop application has 1 executable and 1 .sdf file. It was developed on Win 7 and recently was moved to Win XP system. But that shouldn't be a problem as there are other tables I am inserting into with similar logic and table design.

Do one thin make use of SQL profiler and check the query fire on insert statement.
More on check the database Table again and if possbile set the seed for the primary i.e identity column.

Related

Identity column in view of SQL Server

I have a table in which has a Identity Column.
When I tried to create a view (with only this table), everything is still working fine, the ID property(which is used to mark auto increment number column) of Identity Column is still set to True
When there is only 1 table in view
Here is the diagram
But when I tried to create a view by join the mentioned above table with another table, the Identity Column is automatically set to false.
When I try to join 2 tables in view
Here is the diagram
This problem occurs maybe only in SQL Server 2016 (I tried with SQL Server 2008, it's still working fine)
Did anyone encounter similar problems? How to keep true value of Identity Column in View? Thanks

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.

Transfer data from one database to another database with different schema

i have problem to Transfer data from one sqlserver 2008 r2 to another sql server 2012 databases with different schema, here is some different scenario,
database 1
database 1 with tables Firm and Client, these both have FirmId and ClientId primary key as int datatype,
FirmId is int datatype as reference key used in Client table.
database 2
database 2 with same tables Firm and Client, these both have FirmId and ClientId but primary key as uniqueidentifier,
FirmId is uniqueidentifier datatype as reference key used in Client table.
problem
the problem is not to copy data from 1 database table to 2 database table, but the problem is to maintain the reference key's Firm table into Client table. because there is datatype change.
i am using sql server 2008 r2 and sql server 2012
please help me to resolve / find the solution, i really appreciate your valuable time and effort. thanks
I'll take a stab at it even if I am far from an expert on SQLServer - here is a general procedure (you will have to repeat it for all tables where you have to replace INT with UID, of course...).
I will use Table A to refer to the parent (Firm, if I understand your example clearly) and Table B to refer to the child (Client, I believe).
Delete the relations pointing to Table A
Remove the identity from the id column of Table A
Create a new column with Uniqueidentifier on Table A
Generate values for the Uniqueidentifier column
Add the new Uniqueidentifier column in all the child tables (Table B)
Use the OLD id column to map your child record & update the new Uniqueidentifier value from your parent table.
Drop all the id columns
Recreate the relations
Having said that, I just want to add a warning to you: converting to UID is, according to some, a very bad idea. But if you really need to do that, you can script (and test) the above mentioned procedure.

Resetting the primary key to 1

I have a script for microsoft sql server database which has hundreds of tables and tables contains data as well. This is the database of a web application.what I want to do is to delete the previous records and reset the primary key to 1 or 0.
I have tried
`DBCC CHECKIDENT ('dbo.tbl',RESEED,0); `
but it does not work for me as in most of the tables the primary key is not identity.
I can not truncate the table as its primary key is being used as FK in many other tables.
I have also tried to add the identity specification in the primary key of the table and run the checkident query and then changing it back to non-identity spec, but after adding the record again it starts from where it left.
Making changes in the code is not an option for me.
please help.
According with your question I am not sure about the main objective, Why? If you need truncate a lot of tables and change their structures to have an Identity property why you can't disabled the FK? . In the past I have used an standard process for rebuild a table and migrate all the information, this represent a group of steps, I would try to help you but you should follow the next steps.
Steps:
1) Disable FK for alter the structure of your tables. You can get the solution for this task in the next link:
Temporarily disable all foreign key constraints
2) Alter the table with the new property Identity, this is a classic process of ALTER TABLE xxxxxx.
3) Execute the syntax that previously posted :
DBCC CHECKIDENT ('dbo.tbl',RESEED,0);
Try to follow this path and if you have any problem only ask us.
You can not truncate table that have relation. You shoud remove relation firstly.
My understanding of this question:
You have a database with tables that you want to empty and next have them use primary key values starting at 0 or 1.
Some of these tables use an identity value and you already have a solution for those (you know you can find out which columns have an identity by using the sys.columns view? Look for the is_identity column).
Some tables do not use an identity but get their pk values from an unknown source, which we can't modify.
The only solution I see, is creating an after insert trigger (or modifying) on those tables that subtracts from the new pk value.
E.g.: your "hidden generator" will generate a next value 5254, but you want the next pk value to become one:
CREATE TRIGGER trg_sometable_ai
ON sometable
AFTER INSERT
AS
BEGIN
UPDATE st
SET st.pk_col = st.pk_col - 5253
FROM sometable AS st
INNER JOIN INSERTED AS i
ON i.pk_col = th.pk_col
END
You'll have to determine the next value and thus the "subtract value" for each table.
If the code also inserts child records into tables with a foreign key to this table, and uses the previously generated value, you have to modify those triggers as well...
This is a "last resort" solution and something I would recommend against in any scenario that has other options. Manipulating primary key values is generally not a good idea.

Insert into replicated table fails - identity range check

I'm trying to insert a few thousand rows into a table in a database that is replicated across two servers. From either the publisher or the subscriber, I get the same error:
Msg 548, Level 16, State 2, Line 1
The insert failed. It conflicted with an identity range check constraint in database 'XXX', replicated table 'dbo.NODE_ATTRIB_RSLT', column 'ID'. If the identity column is automatically managed by replication, update the range as follows: for the Publisher, execute sp_adjustpublisheridentityrange; for the Subscriber, run the Distribution Agent or the Merge Agent.
The statement has been terminated.
Checking the constraint on the table, it seems to me like I should be able to insert at least 1000 rows at a time before running into issues. However, I get the same error when trying to insert just a few tens of rows!
Here's how I'm trying to insert data:
insert into NODE_ATTRIB_RSLT
([NODE_ID]
,[ATTRIB_ID]
,[STATE_ID]
,[PLAN_REVISION_ID]
,[TIMESTAMP]
,[VALUE]
,[VALUE_TEXT]
,[LAST_MODIFIED])
SELECT [NODE_ID]
,[ATTRIB_ID]
,[STATE_ID]
,[PLAN_REVISION_ID]
,[TIMESTAMP]
,[VALUE]
,[VALUE_TEXT]
,[LAST_MODIFIED] FROM [NODE_ATTRIB_RSLT_TEMP]
The PK column is an autogenerated identity called ID. To try to insert fewer rows at a time I've added a WHERE clause at the end of the select like so:
WHERE ID >= 1000 and ID <1100
but to no avail.
Running sp_adjustpublisheridentityrange on the Publisher executes successfully but has no effect.
How can I fix this problem with inserts?
How can I modify the ranges of the indentity range contraints to a more reasonable level while leaving the replication running?
I think I worked out what the problem was.
Looking at the properties for the replicated table, it had the standard default identity range of 10000 for the Publisher and 1000 for the Subcriber.
However, checking the identity constraint on the actual table (using SP_HELPCONSTRAINT 'node_attrib_rslt') revealed that there was only a pool of 1000 IDs on both servers. This made the bulk insert fail even when I restricted the number of rows to insert - I'm guessing SQL Server doesn't even get that far when it checks the constraint when running an INSERT INTO.
To fix it I had to do several things:
Change the identity range of the table. I set it up to 20K for both Publisher and Subcriber.
On the Publisher, expand Replication --> Local Publications
Right-click the particular subscription and choose Properties.
Select the Articles page.
Highlight the appropriate Table.
Click on the Article Properties 'button', and choose 'Set Properties of Highlighted Table Article'.
In the Article Properties window, look for Identity Range Management options.
Change the appropriate values.
Press OK and OK on the dialog windows.
Run the sp_adjustpublisheridentityrange stored proc on the Publisher.
New query window on the server
Choose the correct database
Execute sp_adjustpublisheridentityrange #table_name = 'node_attrib_rslt'
From the subcriber, force-synchronise the servers.
On the Subscriber, expand Replication --> Local Subcriptions
Right-click the particular subscription and choose View Subscription Status.
In the dialog that appears, press the monitor button.
In the Replication Monitor window that appears, expand the particular Publisher in the left hand pane.
Click on the Subcription to edit.
In the right hand pane, right-click on the subcription status and choose Start Synchronising.
The status should update to 'Synchronising' while it does its thing.
After it's finished, click on the 'Warnings and Agents' tab. I had a 'Snapshot Agent' listed in the lower pane. Right click on that Agent and start it. After it had been running for a while, the change of properties on the server should have migrated to the client.
Maybe: insert some test rows into the table.
Edit: I've had to do this task again recently, and the constraint on the table would not update until I inserted a bunch of dummy data into the table so as to exhaust the default constraint. Then I resyncronised the servers, and the constraint was updated to the new value.
After that, checking the identity constraint revealed that I finally had a 20K ID range to insert with on both the Publisher and the Subcriber.
I had this exact same issue, and the above solution didn't do anything for me.
Instead what ended up solving the issue was by setting the new, larger identity ranges on the tables in the publication, and then dropping the identity constraints on the table
And then finally running this command that sets the current identity.
DBCC CHECKIDENT ('TableName', RESEED, 1000000000);
Instead of setting the value to 1000000000, the constraint is created again, and set to the correct identity range value currently specified on the table in the publication.
It looks like the CHECKIDENT command forces the constraint to be updated somehow.
The above solution worked for me, but was actually my attempt at just dropping the constraints and setting the publisher and subscriber to use different identity ranges so they would be able to insert rows in the tables. Fortunately the CHECKIDENT seemed to refresh the constraint, something i originally expected the sp_adjustpublisheridentityrange stored procedure to do - except it did nothing.
I ran the above command on both the publisher and the subscriber.

Resources