MS SQL insert into auto increment column default value - sql-server

I am creating a database interface to make some basic operations on tables.
CREATE TABLE products (
ID int IDENTITY(1,1) PRIMARY KEY,
Name VARCHAR(20)
)
As long as I have been using MySQL database, it worked correctly to insert DEFAULT value onto 'ID' column
INSERT INTO products (ID, Name) VALUES (DEFAULT, "ProductName")
But MS SQL won't let me do that, the error I get is DEFAULT or NULL are not allowed as explicit identity values..
I have been looking for solutions and couldn't find one - is there a way to include ID in the list of columns in the insert statement, but actually let the database handle the value to be inserted(auto-increment value)?
The answer to just not include ID in the list of columns is not solving my problem, as I access the database from a C++ program and try to do it as abstract as possible (and some different tables don't have auto-increment on ID)

Two solution :
ignore the ID column in the column list :
INSERT INTO products (Name) VALUES ('ProductName');
do not specify the column list if you want to insert in all columns except identity :
INSERT INTO products VALUES (DEFAULT, ProductName);
By the way, double quote must never be used for strings but only simple quote. Double quote is reserved for "abnormal" objest names...

You must be define the Id column like this:
[id] [int] IDENTITY(1,1) NOT NULL

Related

Identity column in Snowflake

A simple question in Snowflake. I created a table with an identity column.
create table etl_test
(id int identity,
name string);
And tried to insert data into it. In my SQL Server world, I just need to provide the value for the name field.
insert into etl_test values('test');
I tried the same in Snowflake but I am getting an error
SQL compilation error: Insert value list does not match column list expecting 2 but got 1
How can I make sure that the value 'test' is inserted with id = 1?
You need to include the column name(s) you are using if you aren't inserting into all the columns:
insert into etl_test (name) values('test');
"Blind inserts" are antipattern regardless of RDBMS.
In your scenario, you need to specify column list and either remove id from column list or provide a DEFAULT for it.
INSERT INTO etl_test(id, name) VALUES (DEFAULT, 'test');

SQL Server : identity and autoincrement for varchar

This is my first question on this platform. I am working on a database project. I want to use autoincrement for my primary key for id, but also want to add an alphabet before it. Are there other ways to do it apart from using 2 columns declaring one as identity and casting the other? I have worked with stored procedures and triggers.
Thank you
PS: I want to do it using one column if possible
You won't be able to do this with just one column.
The best solution is to use
an ID INT IDENTITY(1,1) column to get SQL Server to handle the automatic increment of your numeric value
a computed, persisted column to convert that numeric value to the value you need
So try this:
CREATE TABLE dbo.tblCompany
(
ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
CompanyID AS 'CMP-' + RIGHT('00000' + CAST(ID AS VARCHAR(5)), 5) PERSISTED,
.... your other columns here....
)
Now, every time you insert a row into tblCompany without specifying values for ID or CompanyID:
INSERT INTO dbo.tblCompany(Col1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)
then SQL Server will increase your ID value, and CompanyID will contain values like CMP-00001, CMP-00002,...... and so on - automatically. The CompanyID column will be fill automatically, by SQL Server, upon inserting a new row - so there's no need for triggers or stored procedures or anything else - just this declaration in your table definition.
UPDATE: if you're using SQL Server 2012 or newer, you can do it with just one column - if you also create a SEQUENCE - like this:
CREATE SEQUENCE SEQ_CompanyID
AS INT
START WITH 1000
INCREMENT BY 1;
CREATE TABLE dbo.Company
(
CompanyID VARCHAR(20) NOT NULL
CONSTRAINT DF_CompanyID
DEFAULT('CMP-' + CAST(NEXT VALUE FOR dbo.SEQ_CompanyID AS VARCHAR(10))),
CompanyName VARCHAR(100) NOT NULL,
----- other columns here
)
Now if you make sure to insert with omitting the CompanyID column in the insert statement, like this:
INSERT INTO dbo.Company (CompanyName)
VALUES ('Company #1'), ('Company ABC'), ('Company Three');
then you get CMP-1001', 'CMP-1002 etc. as your CompanyID, again, automatically handled by SQL Server upon inserting a new row.

INSERT INTO, but retain blank columns?

In a stored procedure I'm creating...
IF OBJECT_ID('tempdb..##SUBOSummary') IS NOT NULL
/*Then it exists*/
DROP TABLE ##SUBOSummary
CREATE TABLE ##SUBOSummary
(
--RowID int not null identity(1,1) primary key,
RowNum int IDENTITY(1,1) NOT NULL,
Dept nvarchar(25) NOT NULL,
Last24 int,
WTD int,
MoTD int,
YTD int
)
I then want to add a series of data from another view, and I'll then fill the rest of the data rows in seperately:
INSERT INTO ##SUBOSummary SELECT DISTINCT vw_EmployeeDepartment.Dept FROM vw_EmployeeDepartment
I'm getting the following error:
Column name or number of supplied values does not match table definition.
I'm hazarding a guess that this is because I'm only populating a single field by the insert statement.
Is there a better way to acheive this?
The error, in truth, is quite clear here:
Column name or number of supplied values does not match table definition.
In your INSERT statement you're implying you want to insert values into all the columns (as you're not specifying which one), yet you're only supplying one column in your SELECT, so where does that value go? SQL Server has no idea.
You need to supply your column(s) in your INSERT clause:
INSERT INTO ##SUBOSummary (Dept)
SELECT DISTINCT vw_EmployeeDepartment.Dept
FROM vw_EmployeeDepartment;
On a different note, however, don't use a Global Temporary Table, they often perform very poorly.

How to use default primary key as a sequence value when creating table for oracle database columns

We have a tool and this tool create some insert scripts to add rows in our plsql table.
this scripts is not modifiable and we can't see this scripts. so,
when data row comes (with insert script that we don't know structure), we should give a primary key. we can use trigger but we don't want do this for reasons of performance.
Below code doesn't work.
CREATE TABLE qname
(
qname_id integer NOT NULL default qname_id_seq.nextval PRIMARY KEY,
);
Any idea?
Thanks..
.nextval cannot be used in Default Value of table, This is achieved by Trigger and Sequence when you want serialized number that anyone can easily read/remember/understand. But if you don't want to manage ID Column (like qname_id) by this way, and value of this column is not much considerable, you can use SYS_GUID() at Table Creation to get Auto Increment like this.
CREATE TABLE qname
(qname_id RAW(16) DEFAULT SYS_GUID() PRIMARY KEY,
name VARCHAR2(30));
(or by Modifying Column)
Now your qname_id column will accept "globally unique identifier value".
you can insert value in table by ignoring emp_id column like this.
INSERT INTO qname (name) VALUES ('name value');
So, it will insert unique value to your qname_id Column.

Auto increment primary key in SQL Server Management Studio 2012

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

Resources