Python pyODBC : Issue inserting into a sql server table with an identity column - sql

An INSERT statement that was created with Python gives me an error when I execute and commit it. I have taken a copy of the statement from Python and run it myself in SQL SERVER and it works fine there. The table I am trying to insert into has an identity column. When Python trys to execute it will give me an error saying what is below when I exclude the identity column in the statement
Table looks like this MY_TABLE ( ID INT IDENTITY(1,1) NOT NULL, A INT, B INT)
INSERT INTO MY_TABLE (A, B) VALUES(VALUE_A, VALUE_B);
"('23000', "[23000] [Microsoft][ODBC SQL Server Driver][SQL Server]Cannot insert the value NULL into column 'MY_IDENTITY_COLUMN', table 'MY_TABLE'; column does not allow nulls. INSERT fails. (515) (SQLExecDirectW); [23000] [Microsoft][ODBC SQL Server Driver][SQL Server]The statement has been terminated. (3621)")"
But when I try to include the value for the Identity column (I don't want to do this) I get the following error which makes sense as it's an identity column that we let the table auto-increment
"Cannot insert explicit value for identity column in table 'MY_TABLE' when IDENTITY_INSERT is set to OFF."
When I run the query in SQL SERVER the table fills the value for the Identity Column itself and auto-increments but for some reason when I run the statement in Python it does not do this and tries to pass a NULL
SQL SERVER version: 10.50.6560.0

Recognising it's a little late but... I had the same problem recently using some old program and ODBC. The solution was to create a View in SQL Server with only the columns required (i.e. A and B in your case) and then insert into that View.

A little hard to tell without your code, but here is an example.
In database create a test table
CREATE TABLE dbo.test(
ID INT IDENTITY NOT NULL PRIMARY KEY,
Name VARCHAR(40) NOT NULL
);
Then in Python specify the columns you are inserting into
import pyodbc
warecn = pyodbc.connect("Your Connection Stuff")
Inscursor = warecn.cursor()
Inscursor.execute("Insert into dbo.test(name) values ('This'), ('is'), ('a'), ('test')")
Inscursor.commit()
Inscursor.close()
del Inscursor
warecn.close()

Related

SQL query regarding Sequence

I made a sequence in Net Beans. But when I tried to insert data in the table I get an error.
My code is:
CREATE SEQUENCE seq_person
MINVALUE 1
START WITH 1
INCREMENT BY 1
INSERT INTO Persons (ID,FirstName,LastName)
VALUES (seq_person.nextval,'Lars','Monsen');
The error is:
[Exception, Error code 30,000, SQLState 42X04] Column
'SEQ_PERSON.NEXTVAL' is either not in any table in the FROM list or
appears within a join specification and is outside the scope of the
join specification or appears in a HAVING clause and is not in the
GROUP BY list. If this is a CREATE or ALTER TABLE statement then
'SEQ_PERSON.NEXTVAL' is not a column in the target table.
The error message Error code 30,000, SQLState 42X04 indicates you are using Derby DB not Oracle. That being the case you need to use Derby syntax for getting the next value. So your insert should look like this:
INSERT INTO Persons (ID,FirstName,LastName)
VALUES (NEXT VALUE FOR seq_person,'Lars','Monsen')

Add nullable column to SQL Server with default value of null

I want to add a nullable boolean column to an existing table with default value of null.
I have used this bit of script but it does not set the default value to null. it sets it to 0 instead.
ADD newColumnName BIT NULL
CONSTRAINT DF_tableName_newColumnName DEFAULT(null)
I just ran your example code snippet on my SQL Server 2008 R2 instance and then inserted a record. It initialized the column to null, as expected. The next step would be to post the alter statement and the insert statement that you used.
I used:
alter table tmp1 Add newColumnName bit null CONSTRAINT DF_tableName_newColumnName DEFAULT(null)
insert into tmp1(emp_id) values(9999)
select * from tmp1
After running the above, I used SQL Server Management Studio "Design" action to examine the properties of the new column. It showed that the "Default Value or Binding" was indeed (Null) as expected.

Insert an auto increment Key to SQL server Compact database

This is my table Produit(ID,libelle,prix). The ID is auto increment, and this is the insert instructions :
cmd.Connection = connexion
cmd.CommandText = "INSERT into Produit_fini(libelle,prix) values (#libelle,#prix)"
cmd.Parameters.AddWithValue("#libelle", libelle)
cmd.Parameters.AddWithValue("#prix", prix)
connexion.Open()
cmd.ExecuteNonQuery()
connexion.Close()
After executing that, an error is occured says that I can't insert NULL value to the ID !?
The column can not contain NULL values. [ Column name = ID,Table name
= Produit_fini ]
How can I insert the ID here ?
It seems like this column ID is not defined with an IDENTITY property. But, you won't be able to alter the table to add the IDENTITY property.
You have to delete the table (if there is no data on it), and create it again with the column ID has IDENTITY(1,1).
You might also need to use this tool Compactview to be able to run statements against SQL Server compact edition database.

IDENTITY_INSERT error while trying to insert data into table

I want to copy data from a table named ActionType inside a database TD_EDD, into another table named ActionType inside another database DsVelocity.
I have written the following query:
INSERT INTO [DsVelocity].[dbo].[ActionType]
([ActionTypeID]
,[ActionTypeName]
,[ActiveStatus])
SELECT [ActionTypeID], [ActionType], [Active/Deactive]
FROM [TD_EDD].[dbo].[ActionType]
GO
Whenever I'm trying to do this, I'm getting the following error:
Msg 544, Level 16, State 1, Line 1
Cannot insert explicit value for identity column in table 'ActionType' when IDENTITY_INSERT is set to OFF.
I don't understand what's wrong and why I'm getting this error?
Note that I'm using Microsoft SQL Server 2008 R2.
This means that when you insert data into target table, you will have conflicting ids. Most likely ActionTypeId column
to Fix it use
INSERT INTO [DsVelocity].[dbo].[ActionType]
([ActionTypeName]
,[ActiveStatus])
SELECT [ActionType], [Active/Deactive]
FROM [TD_EDD].[dbo].[ActionType]
GO
Well, lets assume from the message that ActionTypeID is an IDENTITY Column. You cannot isert values into this column as it is auto generate, uless you use IDENTITY_INSERT
Allows explicit values to be inserted into the identity column of a
table.
At any time, only one table in a session can have the IDENTITY_INSERT
property set to ON. If a table already has this property set to ON,
and a SET IDENTITY_INSERT ON statement is issued for another table,
SQL Server returns an error message that states SET IDENTITY_INSERT is
already ON and reports the table it is set ON for.
If the value inserted is larger than the current identity value for
the table, SQL Server automatically uses the new inserted value as the
current identity value.
The setting of SET IDENTITY_INSERT is set at execute or run time and
not at parse time.
So you would have to do something like
SET IDENTITY_INSERT [DsVelocity].[dbo].[ActionType] ON
before the insert.

SQL Server 2012 temp table OBJECT_ID issue

We have an issue upgrading to SQL Server 2012. I am using the following script to create temporary tables that used to work fine on SQL Server 2008 R2 but now it is generating an error with 2012:
if (OBJECT_ID( 'tempdb..#idstable') > 0)
truncate table #idstable
else
create table #idstable (id int not null)
the error thrown is
There is already an object named '#idstable' in the database.
This is obviously not thrown the first time I use the script (in the same transaction).
Any idea? Thank you!
In SQL Server 2012, #temp tables are created with a negative object_id, so your script won't work as is. The safest way is:
IF OBJECT_ID( 'tempdb..#idstable') IS NOT NULL
(I blogged about this here, and knew it would catch someone.)
Though your script is bound for failure anyway, if it is part of a single batch. The parser will not let you try and create the same #temp table twice.
Try this:
IF OBJECT_ID (N'tempdb..#idstable', N'U') IS NOT NULL
truncate table #idstable
else
create table #idstable (id int not null)
My dears,
This issue is due to the truncate statement. Truncate is used to delete all records preserving the table. Use drop table instead of truncate table and this will works fine ;-)