I am trying to create a table with a column whose AutoIncrement is Yes.
Here is my query not sure what's wrong in it
CREATE TABLE testallcols(SOCycle Text(3), AutoKey integer AUTOINCREMENT NOT NULL, SOData LongBinary NOT NULL)
How do I get my AutoKey column to be an auto increment integer?
AUTOINCREMENT and integer are two different datatypes as far as Access DDL is concerned. Use only AUTOINCREMENT. And to make it function correctly as an autonumber, include the PRIMARY KEY constraint.
This one works without error when tested with ADO/OleDb in Access 2010:
CREATE TABLE testallcols(SOCycle Text(3), AutoKey AUTOINCREMENT PRIMARY KEY, SOData LongBinary NOT NULL)
CREATE TABLE Tblcontacts
(
contactid AUTOINCREMENT(101,1) PRIMARY KEY ,
firstname CHAR (60),
lastname CHAR (60),
email VARCHAR (75)
);
Related
In SQLite:
If a table contains a column of type INTEGER PRIMARY KEY, then that column becomes an alias for the ROWID.
When a new row is inserted into an SQLite table, the ROWID can either be specified as part of the INSERT statement or it can be assigned automatically by the database engine.
If no ROWID is specified on the insert, or if the specified ROWID has a value of NULL, then an appropriate ROWID is created automatically.
I created a table in SQLite with an integer primary key, and then opened the file in LINQPad. I'm trying to insert a new row into the table via C#:
var episode = new RateableItem()
{
SourceId = "tal",
Edition = episodeNum.ToString(),
Name = episodeName,
Consumed = false
};
RateableItems.InsertOnSubmit(episode);
SubmitChanges();
In the above example, I haven't specified the pimary key. This fails because LINQPad has mapped the primary key to a non-nullable int, so the generated SQL inserts a 0 into the primary key, which fails because a row with PK 0 already exists.
Is there a way to configure LINQPad with SQLite so that it passes a null for the PK, allowing SQLite to automatically assign the PK value?
Thanks to the sample database that #sgmoore posted in comments, I was able to find that declaring the table primary key as AUTOINCREMENT solves my issue.
CREATE TABLE RateableItem (
RateableItemId INTEGER PRIMARY KEY AUTOINCREMENT,
SourceId NVARCHAR(32) NOT NULL,
Name NVARCHAR(255),
Edition NVARCHAR(16),
Consumed BOOLEAN NOT NULL
);
When I added AUTOINCREMENT to my table definition, I was able to create a new object without specifying the key. LINQPad's Schema Explorer doesn't show any difference between a primay key with AUTOINCREMENT versus without, but my script compiles and SQLite assigns a value on SubmitChanges().
There are some differences in primary key behavior with AUTOINCREMENT. Fortunately these are fine in my scenario.
var episode = new RateableItem()
{
PrimaryKey = null,
SourceId = "tal",
Edition = episodeNum.ToString(),
Name = episodeName,
Consumed = false
};
How does that work?
How do I auto increment the primary key in a SQL Server database table? I've had a look through the forum but can't see how to do this.
I've looked at the properties but can't see an option. I saw an answer where you go to the Identity specification property and set it to yes and set the Identity increment to 1, but that section is grayed out and I can't change the no to yes.
There must be a simple way to do this but I can't find it.
Make sure that the Key column's datatype is int and then setting identity manually, as image shows
Or just run this code
-- ID is the name of the [to be] identity column
ALTER TABLE [yourTable] DROP COLUMN ID
ALTER TABLE [yourTable] ADD ID INT IDENTITY(1,1)
the code will run, if ID is not the only column in the table
image reference fifo's
When you're creating the table, you can create an IDENTITY column as follows:
CREATE TABLE (
ID_column INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
...
);
The IDENTITY property will auto-increment the column up from number 1. (Note that the data type of the column has to be an integer.) If you want to add this to an existing column, use an ALTER TABLE command.
Edit:
Tested a bit, and I can't find a way to change the Identity properties via the Column Properties window for various tables. I guess if you want to make a column an identity column, you HAVE to use an ALTER TABLE command.
You have to expand the Identity section to expose increment and seed.
Edit: I assumed that you'd have an integer datatype, not char(10). Which is reasonable I'd say and valid when I posted this answer
Expand your database, expand your table right click on your table and select design from dropdown.
Now go Column properties below of it scroll down and find Identity Specification, expand it and you will find Is Identity make it Yes. Now choose Identity Increment right below of it give the value you want to increment in it.
CREATE TABLE Persons (
Personid int IDENTITY(1,1) PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature.
In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record.
Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5).
To insert a new record into the "Persons" table, we will NOT have to specify a value for the "Personid" column (a unique value will be added automatically):
Perhaps I'm missing something but why doesn't this work with the SEQUENCE object? Is this not what you're looking for?
Example:
CREATE SCHEMA blah.
GO
CREATE SEQUENCE blah.blahsequence
START WITH 1
INCREMENT BY 1
NO CYCLE;
CREATE TABLE blah.de_blah_blah
(numbers bigint PRIMARY KEY NOT NULL
......etc
When referencing the squence in say an INSERT command just use:
NEXT VALUE FOR blah.blahsequence
More information and options for SEQUENCE
When you're using Data Type: int you can select the row which you want to get autoincremented and go to the column properties tag. There you can set the identity to 'yes'. The starting value for autoincrement can also be edited there. Hope I could help ;)
I had this issue where I had already created the table and could not change it without dropping the table so what I did was:
(Not sure when they implemented this but had it in SQL 2016)
Right click on the table in the Object Explorer:
Script Table as > DROP And CREATE To > New Query Editor Window
Then do the edit to the script said by Josien; scroll to the bottom where the CREATE TABLE is, find your Primary Key and append IDENTITY(1,1) to the end before the comma. Run script.
The DROP and CREATE script was also helpful for me because of this issue. (Which the generated script handles.)
You can use the keyword IDENTITY as the data type to the column along with PRIMARY KEY constraint when creating the table.
ex:
StudentNumber IDENTITY(1,1) PRIMARY KEY
In here the first '1' means the starting value and the second '1' is the incrementing value.
If the table is already populated it is not possible to change a column to IDENTITY column or convert it to non IDENTITY column. You would need to export all the data out then you can change column type to IDENTITY or vice versa and then import data back.
I know it is painful process but I believe there is no alternative except for using sequence as mentioned in this post.
Be carefull like if you want the ID elements to be contigius or not. As SQLSERVER ID can jump by 1000 .
Examle: before restart ID=11
after restart , you insert new row in the table, then the id will be 1012.
You could do the following: New Table Creation:
-- create new table with Column ID which is Primary Key and Auto Increment --
CREATE TABLE titles(
id INT NOT NULL IDENTITY(1,1) PRIMARY KEY, --Primary Key with Auto-Increment --
keyword VARCHAR(260),
status VARCHAR(10),
);
If you Table Already exists and need to make the changes to ID column to be auto-increment and Primary key, then see below:
ALTER TABLE table DROP COLUMN id; // drop the existing ID in the table
ALTER TABLE table ADD id int IDENTITY(1, 1) NOT NULL; // add new column ID with auto-increment
ALTER TABLE table ADD CONSTRAINT PK_ident_test PRIMARY KEY CLUSTERED (id); // make it primary key
Can someone suggest best method to generate table primary key containing string and a number. Like,
EMP00001
EMP00002
I want to do this by minimizing error possibilities. So should I do this in mysql or with the c# server code. If someone can provide example that would be really helpful.
The idea is to have to columns And the primary key is for them both to be unique like that :
CREATE TABLE yourtable (
characs CHAR(3) Not null DEFAULT 'EMP',
id MEDIUMINT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (characs,id)
) ENGINE=MyISAM;
We have recently added a new "level" to our database - added a key "Company_ID" to be above/before the existing ID Identity field in the tables throughout the database.
For example, if a Table had ID then fields, it now has Company_ID, then ID, then the fields. The idea is that this allows ID to auto-increment for each different Company_ID value that is provided to the functionality (Company_ID 1 can have ID 1, 2, 3 etc ; Company_ID 2 can have ID 1, 2, 3, etc).
The auto-increment field remains as ID. An example table is :
[dbo].[Project](
[Company_ID] [int] NOT NULL,
[ID] [int] IDENTITY(1,1) NOT NULL,
[DescShort] [varchar](100) NULL,
[TypeLookUp_ID] [int] NULL,
[StatusLookUp_ID] [int] NULL,
[IsActive] [bit] NOT NULL,
CONSTRAINT [PK_Project] PRIMARY KEY CLUSTERED
(
[Company_ID] ASC,
[ID] ASC
)
Before the Company_ID was introduced, to perform a CREATE, we simply populated the DescShort, TypeLookUp_ID, StatusLookUp_ID and IsActive fields, and left ID to be whatever it was by default, possibly 0.
The record was saved successfully, and ID was auto-populated by the database, and then used to perform a SHOW via a View, and so on.
Now, however, we want to set Company_ID to a specified value, leave ID, and populate the fields as before.
_db.Project.Add(newProject);
_db.SaveChanges();
Yes, we want to specify the Company_ID value. We want the ID to be auto-populated, as per before.
We are getting the error message :
Cannot insert explicit value for identity column in table "Project"
when IDENTITY_INSERT is set to OFF
Is this caused by specifying the Company_ID, or by the ID field? Do you know how we can rectify this issue?
The problem is on ID. If you set a field as IDENTITY you can't normally assign it a value - the IDENTITY property marks it as allowing the database to automatically assign an incrementing value to the column.
To solve this problem, either remove the automatic IDENTITY property from ID (if you want to auto-increment it, you can always do this in your handling code - get the highest value in the field, add one to it and then assign that value) or go to the DB and set IDENTITY _INSERT on the table, which temporarily allows you to assign values to IDENTITY fields.
SET IDENTITY_INSERT [yourTableName] ON
--go back and run your C# code>
SET IDENTITY_INSERT [yourTableName] OFF
After sleeping, I found this, for Visual Studio c# code : [DatabaseGenerated(DatabaseGeneratedOption.Identity)]. This (in my words), defined for each of my ID fields, tells Visual Studio that the field is an Identity and to "leave it alone" when sending values to the database. When Company_ID occurs first, and has a value, telling Visual Studio that there is an Identity field elsewhere allows the _db.Project.Add(newProject); and then _db.SaveChanges(); to function as required.
This part of the answer is for the Visual Studio side of things. I understand the SQL requirements of IDENTIY_INSERT so thanks to #matt-thrower, #steve-pettifer and the others who contributed.
What worked for me was a simple EDMX update. As I had set Identity Off before and then changed it to auto. But did not update the Edmx . After updating it worked fine.
What worked for me in this instance is to set an attribute on the primary key property in the class:
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int DepartmentId { get; set; }
IDENTITY_INSERT was already on in my DB.
Remove the Identity from Id or add
SET IDENTITY_INSERT [dbo].[Project] ON
Normally the ID is inserted without user interference so you are getting the error because you are trying to enter data in it. Setting it on will allow you to enter the data you want OR, simple turn remove the code where you are entering data into the ID unless if that is something you need
Can you try 2 things and try each seperately?
Remove primary key fields for ID and Company_ID
Take ID column on the first order
Ok, you have a solution already...
but consider to leave ID as unique Primary Key and Company_Id as Foreign Key
The Increment of your Foreign Key in your SQL table is Set automatic ... So when you want to insert any things, you have to delete this Foreign Key from the code like this exemple.
Sql code:
CREATE TABLE [dbo].[annexe1](
[cle] [int] IDENTITY(1,1) NOT NULL,
[tarif] [nvarchar](50) NULL,
[libele] [nvarchar](max) NULL)
Asp.Net code:
InsertCommand = "INSERT INTO [annexe6] ([cle], [tarif], [libele]) VALUES (#cle, #tarif, #libele)"
Correction:
InsertCommand = "INSERT INTO [annexe6] ([tarif], [libele]) VALUES (#tarif, #libele)"
Your ID must be unique. Use some hash for that. (for example GUID)
[Key]
public string Id { get; set; }
public your_constructor()
{
Id = Guid.NewGuid().ToString();
}
take a look if you have an autoincrement field in your table. Put autoincrement to NO and than execute your SQL. After re-put autoincrement in that field and syncronyze again.
I'm trying to insert a new row into a database which has four fields, the first is a primary key set as auto incrementing (integer) and the other three are strings.
I insert a new with the following statement:
INSERT INTO Manufacturer VALUES
('Test1','Test2','01332232321')
But I am given the following exception:
"SQLite error\r\ntable Manufacturer
has 4 columns but 3 values were
supplied"
I assumed that the primary key field can be omitted as the database would automatically assign and increment the value for me.
How would I go about fixing this? Is this a simple syntatical error or do I need to rethink my approach completely?
You have to specify columns:
INSERT INTO Manufacturer (col2, col3, col4) VALUES ('Test1','Test2','01332232321')
or pass the NULL value for primary key column.
I think you're looking for how to AUTOINCREMENT in sqllite
also How do I create an AUTOINCREMENT field