Insert an auto increment Key to SQL server Compact database - sql

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.

Related

Cannot insert data into a table which has an identity constraint [duplicate]

I have the below error when I execute the following script. What is the error about, and how it can be resolved?
Insert table(OperationID,OpDescription,FilterID)
values (20,'Hierachy Update',1)
Error:
Server: Msg 544, Level 16, State 1, Line 1
Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF.
You're inserting values for OperationId that is an identity column.
You can turn on identity insert on the table like this so that you can specify your own identity values.
SET IDENTITY_INSERT Table1 ON
INSERT INTO Table1
/*Note the column list is REQUIRED here, not optional*/
(OperationID,
OpDescription,
FilterID)
VALUES (20,
'Hierachy Update',
1)
SET IDENTITY_INSERT Table1 OFF
don't put value to OperationID because it will be automatically generated. try this:
Insert table(OpDescription,FilterID) values ('Hierachy Update',1)
Simply If you getting this error on SQL server then run this query-
SET IDENTITY_INSERT tableName ON
This is working only for a single table of database
e.g If the table name is student then query look like this:
SET IDENTITY_INSERT student ON
If you getting this error on your web application or you using entity framework then first run this query on SQL server and Update your entity model (.edmx file) and build your project and this error will be resolved
Be very wary of setting IDENTITY_INSERT to ON. This is a poor practice unless the database is in maintenance mode and set to single user. This affects not only your insert, but those of anyone else trying to access the table.
Why are you trying to put a value into an identity field?
In your entity for that table, add the DatabaseGenerated attribute above the column for which identity insert is set:
Example:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int TaskId { get; set; }
There are basically 2 different ways to INSERT records without having an error:
1) When the IDENTITY_INSERT is set OFF. The PRIMARY KEY "ID" MUST NOT BE PRESENT
2) When the IDENTITY_INSERT is set ON. The PRIMARY KEY "ID" MUST BE PRESENT
As per the following example from the same Table created with an IDENTITY PRIMARY KEY:
CREATE TABLE [dbo].[Persons] (
ID INT IDENTITY(1,1) PRIMARY KEY,
LastName VARCHAR(40) NOT NULL,
FirstName VARCHAR(40)
);
1) In the first example, you can insert new records into the table without getting an error when the IDENTITY_INSERT is OFF. The PRIMARY KEY "ID" MUST NOT BE PRESENT from the "INSERT INTO" Statements and a unique ID value will be added automatically:. If the ID is present from the INSERT in this case, you will get the error "Cannot insert explicit value for identify column in table..."
SET IDENTITY_INSERT [dbo].[Persons] OFF;
INSERT INTO [dbo].[Persons] (FirstName,LastName)
VALUES ('JANE','DOE');
INSERT INTO Persons (FirstName,LastName)
VALUES ('JOE','BROWN');
OUTPUT of TABLE [dbo].[Persons] will be:
ID LastName FirstName
1 DOE Jane
2 BROWN JOE
2) In the Second example, you can insert new records into the table without getting an error when the IDENTITY_INSERT is ON. The PRIMARY KEY "ID" MUST BE PRESENT from the "INSERT INTO" Statements as long as the ID value does not already exist: If the ID is NOT present from the INSERT in this case, you will get the error "Explicit value must be specified for identity column table..."
SET IDENTITY_INSERT [dbo].[Persons] ON;
INSERT INTO [dbo].[Persons] (ID,FirstName,LastName)
VALUES (5,'JOHN','WHITE');
INSERT INTO [dbo].[Persons] (ID,FirstName,LastName)
VALUES (3,'JACK','BLACK');
OUTPUT of TABLE [dbo].[Persons] will be:
ID LastName FirstName
1 DOE Jane
2 BROWN JOE
3 BLACK JACK
5 WHITE JOHN
you can simply use This statement for example if your table name is School.
Before insertion make sure identity_insert is set to ON and after insert query turn identity_insert OFF
SET IDENTITY_INSERT School ON
/*
insert query
enter code here
*/
SET IDENTITY_INSERT School OFF
Note that if you are closing each line with ;, the SET IDENTITY_INSERT mytable ON command will not hold for the following lines.
i.e.
a query like
SET IDENTITY_INSERT mytable ON;
INSERT INTO mytable (VoucherID, name) VALUES (1, 'Cole');
Gives the error
Cannot insert explicit value for identity column in table 'mytable' when IDENTITY_INSERT is set to OFF.
But a query like this will work:
SET IDENTITY_INSERT mytable ON
INSERT INTO mytable (VoucherID, name) VALUES (1, 'Cole')
SET IDENTITY_INSERT mytable OFF;
It seems like the SET IDENTITY_INSERT command only holds for a transaction, and the ; will signify the end of a transaction.
If you are using liquibase to update your SQL Server, you are likely trying to insert a record key into an autoIncrement field. By removing the column from the insert, your script should run.
<changeSet id="CREATE_GROUP_TABLE" >
<createTable tableName="GROUP_D">
<column name="GROUP_ID" type="INTEGER" autoIncrement="true">
<constraints primaryKey="true"/>
</column>
</createTable>
</changeSet>
<changeSet id="INSERT_UNKNOWN_GROUP" >
<insert tableName="GROUP_D">
<column name="GROUP_ID" valueNumeric="-1"/>
...
</insert>
</changeSet>
everyone comment about SQL, but what happened in EntityFramework? I spent reading the whole post and no one solved EF. So after a few days a found solution:
EF Core in the context to create the model there is an instruction like this: modelBuilder.Entity<Cliente>(entity => { entity.Property(e => e.Id).ValueGeneratedNever();
this produces the error too, solution: you have to change by ValueGeneratedOnAdd() and its works!
There is pre-mentioned OperationId in your query which should not be there as it is auto increamented
Insert table(OperationID,OpDescription,FilterID)
values (20,'Hierachy Update',1)
so your query will be
Insert table(OpDescription,FilterID)
values ('Hierachy Update',1)
The best solution is to use annotation GeneratedValue(strategy = ...), i.e.
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column ...
private int OperationID;
it says, that this column is generated by database using IDENTITY strategy and you don't need to take care of - database will do it.
Another situation is to check that the Primary Key is the same name as with your classes where the only difference is that your primary key has an 'ID' appended to it or to specify [Key] on primary keys that are not related to how the class is named.
This occurs when you have a (Primary key) column that is not set to Is Identity to true in SQL and you don't pass explicit value thereof during insert. It will take the first row, then you wont be able to insert the second row, the error will pop up. This can be corrected by adding this line of code [DatabaseGenerated(DatabaseGeneratedOption.Identity)] in your PrimaryKey column and make sure its set to a data type int. If the column is the primary key and is set to IsIDentity to true in SQL there is no need for this line of code [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
this also occurs when u have a column that is not the primary key, in SQL that is set to Is Identity to true, and in your EF you did not add this line of code [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
If you're having this issue while using an sql-server with the sequelize-typescript npm make sure to add #AutoIncrement to ID column:
#PrimaryKey
#AutoIncrement
#Column
id!: number;
I solved this problem by creating a new object every time I want to add anything to the database.
In my case I was having set another property as key in context for my modelBuilder.
modelBuilder.Entity<MyTable>().HasKey(t => t.OtherProp);
I had to set the proper id
modelBuilder.Entity<MyTable>().HasKey(t => t.Id);
EF Core 3.x
Referencing Leniel Maccaferri, I had a table with an Autoincrementing attribute called ID(original primary key) and another attribute called Other_ID(The new primary Key). Originally ID was the primary key but then Other_ID needed to be the new Primary key. Since ID was being used in other parts of the application I could not just remove it from Table. Leniel Maccaferri solution only worked for me after I added the following snippet:
entity.HasKey(x => x.Other_ID);
entity.Property(x => x.ID).ValueGeneratedOnAdd();
Full Code snippet Below (ApplicationDbContext.cs):
protected override void OnModelCreating(ModelBuilder builder)
{
builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
base.OnModelCreating(builder);
builder.Entity<tablename>(entity =>
{
entity.HasKey(x => x.Other_ID);
entity.Property(x => x.ID).ValueGeneratedOnAdd();
entity.HasAlternateKey(x => new { x.Other_ID, x.ID });
});
}
First Go to the required table name
Step 2 -> right click on the table name
step 3 --> Select Design
step 4 --> Click on the column name
step 5) go to the column properties then Set No to the Identity Specification
[Note: After insert to the explicit value if you want you can revert back to identity specification true then again it will generate the value]
if you using SQL server management studio you can use below method
Step 1)
step 2)
Even if everything was correct, this error can appear if the data type of Identity column is not int or long. I had identity column as decimal, although I was only saving int values (my bad). Changing data type in both database and underlying model fixed the issue for me.
Put break point on your [HttpPost] method and check what value is being passed to Id property. If it is other than zero then this error will occur.
First thing first...
You need to know why you are getting the error in the first place.
Lets take a simple HttpPost of JSON Data that looks like this:
{
"conversationID": 1,
"senderUserID": 1,
"receiverUserID": 2,
"message": "I fell for the wrong man!",
"created":"2022-02-14T21:18:11.186Z"
}
If you generated your database using Entity framework core while connecting to SQLServer or any other database server, the database automatically takes the responsibility of updating and auto-generating the Key/Unique identifier of the Identity Column, which in most cases is an integer value it auto-increments.
To safely post your data using the in-built conventions which keeps you at a safer end, just remove the ID field from the data you want to send to the database, and let the database engine and ef-core do the heavy lifting which they are designed to do.
So the proper way to post the data would be:
{
"senderUserID": 1,
"receiverUserID": 2,
"message": "I fell for the wrong man!",
"created":"2022-02-14T21:18:11.186Z"
}
You would notice I took out the ConversationID.
You can learn more about entity framework on this website : https://entityframeworkcore.com
I hope you stick more to conventions than configuration in your apps. Knowing how to do things with already proven standards and conventions will save you a lot of working hours.
And if you are using Oracle SQL Developer to connect, remember to add /sqldev:stmt/
/sqldev:stmt/ set identity_insert TABLE on;
I'm not sure what the use for the "Insert Table" is, but if you're just trying to insert some values try:
Insert Into [tablename] (OpDescription,FilterID)
values ('Hierachy Update',1);
I had the same error message come up, but I think this should work. The ID should auto-increment automatically as long as it's a primary key.
In my CASE I was inserting more character than defined in table.
In My Table column was defined with nvarchar(3) and I was passing more than 3 characters and same ERROR message was coming .
Its not answer but may be in some case problem is similar
im using asp.net core 5.0 and i get that error. i get that error because i was adding another data and triggering the other .SaveChanges() method like below :
_unitOfWorkVval.RepositoryVariantValue.Create(variantValue);
int request = HttpContext.Response.StatusCode;
if (request == 200)
{
int tryCatch = _unitOfWorkCVar.Complete();
if (tryCatch != 0)
{
productVariant.CategoryVariantID = variantValue.CategoryVariantID;
productVariant.ProductID = variantValue.ProductID;
productVariant.CreatedDate = DateTime.Now;
_unitOfWorkProductVariant.RepositoryProductVariant.Create(productVariant);
_unitOfWorkVval.RepositoryVariantValue.Create(variantValue);
int request2 = HttpContext.Response.StatusCode;
if(request==200)
{
int tryCatch2=_unitOfWorkProductVariant.Complete();//The point where i get that error
}///.......
Had the same issue using Entity Framework with a model like this (I simplified the original code):
public class Pipeline
{
public Pipeline()
{
Runs = new HashSet<Run>();
}
public int Id {get; set;}
public ICollection<Run> Runs {get;set;}
}
public class Run
{
public int Id {get; set;}
public int RequestId {get; set;}
public Pipeline Pipeline {get;set;}
}
The Run has a many-to-1 relation to the Pipeline (one Pipeline can run multiple times)
In my RunService I have injected the DbContex as context. The DbContext had a Runs DbSet. I implemented this method in the RunService:
public async Task<Run> CreateAndInit(int requestId, int pplId)
{
Pipeline pipeline = await pipelineService.Get(pplId).FirstOrDefaultAsync().ConfigureAwait(false);
Run newRun = new Run {RequestId = requestId, Pipeline = pipeline};
context.Runs.Add(newRun);
await context.SaveChangesAsync().ConfigureAwait(false); // got exception in this line
return newRun;
}
As the method executed, I got this exception:
Exception has occurred: CLR/Microsoft.EntityFrameworkCore.DbUpdateException
Exception thrown: 'Microsoft.EntityFrameworkCore.DbUpdateException' in System.Private.CoreLib.dll: 'An error occurred while updating the entries. See the inner exception for details.'
Inner exceptions found, see $exception in variables window for more details.
Innermost exception Microsoft.Data.SqlClient.SqlException : Cannot insert explicit value for identity column in table 'Pipelines' when IDENTITY_INSERT is set to OFF.
For me, the solution was to separate the creation of the object and relation
public async Task<Run> CreateAndInit(int requestId, int pplId)
{
Pipeline pipeline = await pipelineService.Get(pplId).FirstOrDefaultAsync().ConfigureAwait(false);
Run newRun = new Run {RequestId = requestId};
context.Runs.Add(newRun);
newRun.Pipeline = pipeline; // set the relation separately
await context.SaveChangesAsync().ConfigureAwait(false); // no exception
return newRun;
}
In my case the problem was, that I specified the autoincrement ID by myself from the code when I tried to update the records.
After removing the ID property from new record creation, then everything worked fine.
You can not insert data in OperationID column when you set identity increment for this field.
Do not enter a value in this field, it will be set automatically.
Insert table(OpDescription,FilterID)
values ('Hierachy Update',1)
The problem raised from using non-typed DBContext or DBSet if you using Interface and implement method of savechanges in a generic way
If this is your case I propose to strongly typed DBContex for example
MyDBContext.MyEntity.Add(mynewObject)
then .Savechanges will work

Insert into a table containing only identity column

I have the following table :
CREATE TABLE Seq2 (val INT NOT NULL IDENTITY);
How to populate this table knowing that I tried this :
INSERT INTO Seq2(val) VALUES (1)
I have the following error :
Cannot insert explicit value for identity column in table 'Seq2' when
IDENTITY_INSERT is set to OFF.
Having such a table seems completely pointless, if I must say. If the table has only an IDENTITY then it effectively holds no meaning, so there's no point it being there.
That being said, if you did have such a table, you can INSERT values into the IDENTITY using DEFAULT VALUES:
INSERT INTO dbo.Seq2
DEFAULT VALUES;
INSERT INTO dbo.Seq2
DEFAULT VALUES;
With a new table, this would create rows with the values 1 and 2.
If you want to explicitly INSERT values into the table, then you're better off remove the IDENTITY option. Considering this is a new table, just DROP it and recreate it with the IDENTITY property:
DROP TABLE dbo.Seq2;
GO
CREATE TABLE Seq2 (val INT NOT NULL);
Having a table with a single IDENTITY column, that you're then going to define the results for really is pointless. Either don't use IDENTITY and define the values, or use IDENTITY and let SQL Server handle it.
SET IDENTITY_INSERT Seq2 ON
INSERT INTO Seq2(val)VALUES (1)
SET IDENTITY_INSERT Seq2 OFF
Simply, enable IDENTITY_INSERT for the table. That looks like this:
SET IDENTITY_INSERT IdentityTable ON
INSERT INTO Seq2(val) VALUES (1)
SET IDENTITY_INSERT IdentityTable OFF
Keep in mind :
It can only be enabled on one table at a time. If you try to enable
it on a second table while it is still enabled on a first table SQL
Server will generate an error.
When it is enabled on a table you must specify a value for the
identity column.
The user issuing the statement must own the object, be a system
administrator (sysadmin role), be the database owner (dbo) or be a
member of the db_ddladmin role in order to run the command.
SELECT SCOPE_IDENTITY() // to get last identity value generated in the same session and scope
SELECT ##IDENTITY // to get the last identity vaue generated in a session irrespective of scope

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

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()

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.

How to increment ID by 1 in SQL Server (backend) when INSERT code is written in vba (frontend)?

I am new to this forum.
I have the following environment: an Access frontend client that is connected to a database on SQL Server (backend). I would like to use an Access form to enter data that is associated with a specific ID number (in database Table). Ideally the ID will automatically increment when an INSERT is made to the Table. The vba code (based on the SQL query) I wrote is the following:
Option Compare Database
Option Explicit
Private Sub List0_Click()
Dim HelloWORLD As String
Dim dbsCurrent As Database
Set dbsCurrent = CurrentDb
CurrentDb.Execute "INSERT INTO Table1 (TESTING_1, TESTING_2) VALUES (" & 9 & "," & HelloWORLD & ")"
End Sub
The code is compiling but it is not appending the Table1 like it is supposed to do. Please Help.
You can use sequences.
You can creates sequence MySequence1 and use it:
CurrentDb.Execute "INSERT INTO Table1 (TESTING_1, TESTING_2) VALUES (NEXT VALUE FOR MyDemoSequence," & HelloWORLD & ")"
Can you make the ID field an IDENTITY field within SQL Server? This will automatically increment whenever a new row is inserted. Example from Microsoft documentation:
CREATE TABLE new_employees
(
id_num int IDENTITY(1,1),
fname varchar (20),
minit char(1),
lname varchar(30)
)
The first number is the seed, and the second is the increment, so IDENTITY(1,1) means start at '1', and increase by '1' each time.
You can retrieve the ID that was created using SELECT SCOPE_IDENTITY(); following the insert if necessary.