How to insert existing data into auto-incrementing field - sql-server

I used the SMAA to upsize an Access 2010 database to SQL Server 2005.
During the process a number of records were not imported into SQL Server due to some corrupt or illegal data. I have since cleaned up the data that was not imported and saved it to a temporary table in the database. I now want to insert that data into the original table. However, one of the fields, called Task_ID, is an auto-incrementing field. When I run a standard insert query, the resulting data auto-incremented and does not use the imported Task_ID value. Is there a way to get this data into the field without it being changed?

Enable insertion of existing data for the upload, then turn it off again.
http://technet.microsoft.com/en-us/library/aa259221(v=sql.80).aspx explains how:
Basically it is a SQL commmand. The syntax is:
SET IDENTITY_INSERT [ database. [ owner. ] ] { table } { ON | OFF }

Wrap the INSERT statements with the SET IDENTITY_INSERT command:
SET IDENTITY_INSERT [table_name] ON
...
SET IDENTITY_INSERT [table_name] OFF

Related

Enable identity insert is not working when importing data

I am trying to import many tables from access db to MS SQL server using the import wizard.
Some rows in source tables has been deleted so the sequence of IDs are like this: 2,3,5,8,9,12,...
but when I import the data into my destination, the IDs start from 1 and increment by 1, so they don't exactly match with source data.
I even check the "Enable Identity insert" but it does not help.
The only work around I have found is to change the IDs in destination tables from Identity to integer one by one, then import, and then change them back to identity, which is very time consuming.
Is there any better way to do this?
If you want to insert an id in the identity column, you need to use:
SET IDENTITY_INSERT table_name ON
https://msdn.microsoft.com/es-us/library/ms188059.aspx
Remember to set it OFF at the end of the script.

How to merge table from access to SQL Express?

I have one table named "Staff" in access and also have this table(same name) in SQL 2008.
Both table have thousands of records. I want to merge records from the access table to sql table without affecting the existing records in sql. Normally, I just export using OCBC driver and that works fine if that table doesn't exist in sql server. Please advise. Thanks.
A simple append query from the local access table to the linked sql server table should work just fine in this case.
So, just drop in the first (from) table into the query builder. Then change the query type to append, and you are prompted for the append table name.
From that point on, just drop in the columns you want (do not drop in the PK column, as they need not be used nor transferred in this case).
You can also type in the sql directly in the query builder. Either way, you will wind up with something like:
INSERT INTO dbo_custsql
( ADMINID, Amount, Notes, Status )
SELECT ADMINID, Amount, Notes, Status
FROM custsql1;
This may help: http://www.red-gate.com/products/sql-development/sql-compare/
Or you could write a simple program to read from each data set and do the comparison, adding, updating, and deleting, etc.

Cannot insert duplicate record in a table

I am trying to execute stored proc through SSIS and it gives me following error:
[Execute SQL Task] Error: Executing
the query "Exec sp1 ?" failed with
the following error: "Procedure: sp1
Line: 66 Message: Cannot insert
duplicate key row in object
'table.sq1' with unique index
'UIX_sp1_Key'.". Possible failure
reasons: Problems with the query,
"ResultSet" property not set
correctly, parameters not set
correctly, or connection not
established correctly.
Actually the stored Proc sp1 is truncating & reloading a data into a table.
I am not able to figure out where exactly its trying to insert duplicate record.
Thanks in advance.
Your data must have duplicate values across the key column(s). You could remove the primary key temporarily (or create another table with the same structure but without the definition of the primary key, but that would mean changing the stored procedure), then load the data into the table. Then use this SQL statement:
select keycol1 {,keycol2 {,keycol3} ...}, count(*)
from tablename
group by keycol1 {,keycol2 {,keycol3} ...}
having count(*) > 1
That will show you the data values that are duplicates across the key column(s).
If you are truncating the table before load, then you must have duplicate data in the source.
Examine this to see what there is. use Excel or Access or some such if needed to assist. Or drop the unique constraint then query the staging table with an aggregate query.

Turn off IDENTITY_INSERT for Dataset insert

I am using a dataset to insert data being converted from an older database. The requirement is to maintain the current Order_ID numbers.
I've tried using:
SET IDENTITY_INSERT orders ON;
This works when I'm in SqlServer Management Studio, I am able to successfully
INSERT INTO orders (order_Id, ...) VALUES ( 1, ...);
However, it does not allow me to do it via the dataset insert that I'm using in my conversion script. Which looks basically like this:
dsOrders.Insert(oldorderId, ...);
I've run the SQL (SET IDENTITY_INSERT orders ON) during the process too. I know that I can only do this against one table at a time and I am.
I keep getting this exception:
Exception when attempting to insert a value into the orders table
System.Data.SqlClient.SqlException: Cannot insert explicit value for identity column in table 'orders' when IDENTITY_INSERT is set to OFF.
Any ideas?
Update
AlexS & AlexKuznetsov have mentioned that Set Identity_Insert is a connection level setting, however, when I look at the SQL in SqlProfiler, I notice several commands.
First - SET IDENTITY_INSERT DEAL ON
Second - exec sp_reset_connection
Third to n - my various sql commands including select & insert's
There is always an exec sp_reset_connection between the commands though, I believe that this is responsible for the loss of value on the Identity_Insert setting.
Is there a way to stop my dataset from doing the connection reset?
You have the options mixed up:
SET IDENTITY_INSERT orders ON
will turn ON the ability to insert specific values (that you specify) into a table with an IDENTITY column.
SET IDENTITY_INSERT orders OFF
Turns that behavior OFF again and the normal behavior (you can't specify values for IDENTITY columns since they are auto-generated) is reinstated.
Marc
You want to do SET IDENTITY_INSERT ON to allow you to insert into identity columns.
It seems a bit backwards, but that's the way it works.
It seems that you're doing everything right: SET IDENTITY_INSERT orders ON is the right way on SQL Server's side. But the problem is that you're using datasets. From the code you've provided I can say that you're using typed dataset - the one that was generated in Visual Studio based on the database.
If this is the case (most likely) then this dataset contains a constraint that does not allows you to set values for orderId field, i.e. it's the code that does not allow specifying explicit value, not SQL Server. You should go to dataset designer and edit properties of orderId field: set AutoIncrement and ReadOnly to false. But the same changes can be performed in run time. This will allow you to add a row with explicit value for orderId to a dataset and later save it to SQL Server table (you will still need SET IDENTITY_INSERT).
Also note that IDENTITY_INSERT is a connection-level setting so you need to be sure that you're executing corresponding SET exactly for the same connection that you will be using to save your changes to the database.
I would use Profiler to determine whether your SET IDENTITY_INSERT orders ON;
is issued from the same connection as your subsequent inserts, as well as the exact SQL being executed during inserts.
AlexS was correct, the problem was the Insert_Identity worked, but it is a connection level setting, so I needed to set the Insert_Identity within a transaction.
I used Ryan Whitaker's TableAdapterHelper code
and I created an update command on my tableadapter that ran the Identity_Insert. I then had to create a new Insert command with the Identity column specified. I then ran this code
SqlTransaction transaction = null;
try
{
using (myTableAdapter myAdapter = new myTableAdapter())
{
transaction = TableAdapterHelper.BeginTransaction(myAdapter);
myAdapter.SetIdentityInsert();
myAdapter.Insert(myPK,myColumn1,myColumn2,...);
}
transaction.Commit();
}
catch(Exception ex)
{
transaction.Rollback();
}
finally
{
transaction.Dispose();
}
In case that you still have problems with "insert_identity" , you can try to use a complete insert statement like:
insert into User(Id, Name) values (1,'jeff')

How can I change a field in a SQL server database that's set to "Read Only Cell"?

I have a SQL database that has a table with a field set to "Read Only" when I look at it through Microsoft SQL Server Management Studio Express.
I need to change some data within that field manually but I can't see any properties that I can change that will let me override this.
Will I need to write a sql script on the table to do this or is there something that I am missing ?
What is the datatype of the field? You may not be able to "type" into it if its of an ntext or image datatype and management studio can't handle the size of it.
In that case you might have no option but to perform an update as follows.
UPDATE TableName SET ColumnName = 'NewValue' WHERE PrimaryKeyId = PrimaryKeyValue
The field is most likely "read-only" because it contains a calculated value.
If that's the case, you would have to change calculation in the table definition to change it's value.
This problem will occur when you set a particular field as Primary Key and you set it into 'Is Identity' is true, that means that field will automatically incremented whenever an insertion is takes placed...So better to check whether it is auto increment or not.. If it is ,then change that property 'Is Idenitity' as false.
In an SQL query I had once, the query I used to generate the table to edit included a join to a table on a "Server Object", specifically a linked server. This marked the cells as read only, even though the table on which I was actually going to change the data wasn't on the linked server.
My resolution: Luckily I was able to adjust the query so I didn't need to do the JOIN with a linked table and then I could edit the cells.
Suggestion: Check your query for linked servers or other odd statements that may lock your table.
Use trigger in order to prevent this column updating:
CREATE TRIGGER UpdateRecord ON my_table
AFTER UPDATE AS UPDATE my_table
SET [CreatedDate] = ((SELECT TOP 1 [CreatedDate] FROM Deleted d where d.[id]=[id]))

Resources