SQL create statement incorrect syntax near auto increment - sql

I created the following table, but I got the error below;
Incorrect syntax near 'AUTO_INCREMENT'.
SQL:
CREATE TABLE [dbo].[MY_TABLE] (
[ID] INT NOT NULL AUTO_INCREMENT,
[NAME] NVARCHAR (100) NULL,
[SCHOOL] NVARCHAR (100) NULL,
PRIMARY KEY (ID)
);
I think I have done everything right. Can someone help me out?

It is IDENTITY not AUTO_INCREMENT in SQL Server.
Try this instead:
CREATE TABLE [dbo].[MY_TABLE] (
[ID] INT NOT NULL IDENTITY(1, 1),
[NAME] NVARCHAR (100) NULL,
[SCHOOL] NVARCHAR (100) NULL,
PRIMARY KEY (ID)
);

Its not AUTO_INCREMENT. Here the Demo from sqlfiddle

Use IDENTITY for MSSQL as shown below. *AUTO_INCREMENT is for MySQL and MariaDB:
CREATE TABLE [dbo].[MY_TABLE] (
[ID] INT NOT NULL IDENTITY, -- Here
...
);
In addition, you can have a custom IDENTITY with "()" as shown below. The 1st argument is for start value and the 2nd argument is for increment value so in the example below, if first inserting a row, ID is 20 and if second inserting a row, ID is 23, then ID is 26, 29, 32...:
-- Increment value
CREATE TABLE [dbo].[MY_TABLE] (-- ↓
[ID] INT NOT NULL IDENTITY(20, 3),
... -- ↑
); -- Start value
And, IDENTITY is equivalent to IDENTITY(1, 1).

Related

Incorrect syntax in SQL Server query

CREATE TABLE identity (
empid VARCHAR(255) PRIMARY KEY,
entry VARCHAR(255)
);
-- Table: vectors
CREATE TABLE vectors (
f_id INTEGER PRIMARY KEY IDENTITY(1,1),
label STRING NOT NULL,
empid STRING REFERENCES identity (empid)
NOT NULL,
vector BLOB NOT NULL
);
I tried to run the above query but it gives me error
Incorrect syntax near expected '.', ID or QUOTED_ID.
I don't understand why it is giving me this error, is it because IDENTITY is a keyword in SQL Server. Kindly help!
Try this:
CREATE TABLE [identity] (
empid VARCHAR(255) PRIMARY KEY,
entry VARCHAR(255)
);
-- Table: vectors
CREATE TABLE vectors (
f_id INTEGER PRIMARY KEY IDENTITY(1,1),
label VARCHAR(255) NOT NULL,
empid VARCHAR(255) REFERENCES [identity] (empid)
NOT NULL,
vector VARCHAR(255) NOT NULL
);
Also, if you are working with SQL Server Management Studio, you can see that some words are colored in blue. It will be better to avoid them using in your code as names of tables, variables and other objects. For example, identity is such word.

SERIAL fields / Auto increment

The task indicated this:
Create a table named automagic with the following fields:
An id field is an auto-incrementing serial field.
A name field that allows up to 32 characters but no more This field is required.
A height field is a floating-point number that is required.
And my code was:
CREATE TABLE automatic (
id SERIAL PRIMARY KEY NOT NULL,
name CHAR (32),
height numeric);
However, the self-rater answered this Expecting an INSERT without a height to fail, it did not fail.
After that, I tried this
CREATE TABLE automatic (
id int not null auto_increment primary key,
name varchar(32) not null,
height float not null);
And got
ERROR: syntax error at or near "auto_increment"
LINE 1: CREATE TABLE automagic (id int not null auto_increment prima...\
SQL state: 42601
Character: 41
You can try something like this:
CREATE TABLE automagic (
id int NOT NULL,
name varchar(32) NOT NULL,
height float NOT NULL
);
CREATE SEQUENCE automagic_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER SEQUENCE automagic_id_seq OWNED BY automagic.id;
ALTER TABLE ONLY automagic ALTER COLUMN id SET DEFAULT nextval('automagic_id_seq'::regclass);
EDIT:
As pointed out by #a_horse_with_no_name, this is better:
CREATE TABLE automagic (
id int GENERATED ALWAYS AS IDENTITY,
name varchar(32) NOT NULL,
height float NOT NULL
);
maybe try this:
CREATE TABLE automagic (
id SERIAL,
name VARCHAR(32) NOT NULL,
height FLOAT NOT NULL)
Use primary key.
CREATE TABLE automagic (
id SERIAL primary key,
name VARCHAR(32) NOT NULL,
height FLOAT NOT NULL)

SQL auto increment pgadmin 4

I am trying to make a simple database with an number generator but why do I get the error below?
ERROR: syntax error at or near "AUTO_INCREMENT"
LINE 2: IDNumber int NOT NULL AUTO_INCREMENT,
Code:
CREATE TABLE Finance
(
IDNumber int NOT NULL AUTO_INCREMENT,
FinName varchar(50) NOT NULL,
PRIMARY KEY(IDNumber)
);
The subject of the question mentions pgAdmin 4, so here's how to do it there.
First, add a column to your table, then click the little edit icon:
Then go to Constraints and select the Identity type:
This generates SQL similar to this:
CREATE TABLE public.my_table_name
(
id integer NOT NULL GENERATED ALWAYS AS IDENTITY,
PRIMARY KEY (id)
);
For Postgres you have to use SERIAL
CREATE TABLE Finance
(
IDNumber SERIAL PRIMARY KEY,
FinName varchar(50) NOT NULL
);
IN pgadmin-2.
step 01:
create seq:
and set info:
step 02: go to ID in table and set constraints
if it is sql the syntax is the following
CREATE TABLE Persons (
ID int IDENTITY(1,1) PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
You are using a MySQL syntax which won't work in SQL Server.
CREATE TABLE Finance
(
IDNumber int NOT NULL IDENTITY(1,1) PRIMARY KEY,
FinName varchar(50) NOT NULL
);
The following code should work for SQL Server.
IDENTITY(1,1) is SQL Server's way of saying "auto increment".
The starting value for IDENTITY is 1, and it will increment by 1 for each new record.
So : IDENTITY(startvalue, incrementvalue)
there are two options; one is to use the "datatype" serial or create a sequence and use this sequence as a default value for your integer as follows:
CREATE SEQUENCE your_seq;
CREATE TABLE foo(
id int default nextval('your_seq'::regclass),
other_column TEXT);
INSERT INTO foo(other_column) VALUES ('bar') RETURNING *;
It is important to note that specifying a table as follows:
CREATE TABLE tablename (
colname SERIAL);
is equivalent to:
CREATE SEQUENCE tablename_colname_seq AS integer;
CREATE TABLE tablename (
colname integer NOT NULL DEFAULT nextval('tablename_colname_seq'));
ALTER SEQUENCE tablename_colname_seq OWNED BY tablename.colname;
More information about serial can be found here.

Cannot insert the value NULL into column 'Id' although Id is set

I have a strange problem.
I want to insert an item to a table from database. I use Entity Framework.
Although the Id is set, I keep getting the following error:
Cannot insert the value NULL into column 'Id', table 'project_atp.dbo.ShoppingCarts'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated."}
The table definition:
CREATE TABLE [dbo].[ShoppingCarts] (
[Id] INT NOT NULL,
[Guid] UNIQUEIDENTIFIER NULL,
[Name] NVARCHAR (255) NULL,
[Code] NVARCHAR (255) NULL,
[SupplierNo] NVARCHAR (255) NULL,
[SupplierName] NVARCHAR (255) NULL,
[Price] NVARCHAR (50) NULL,
[Quantity] INT NULL,
CONSTRAINT [PK_ShoppingCarts] PRIMARY KEY CLUSTERED ([Id] ASC)
);
Can you please advise what could be wrong here! Thanks!
By default Entity Framework assumes that an integer primary key is database generated. As the result Entity Framework would not include Primary Key field in the actual INSERT statement.
I would try to either play along and ALTER the table to auto-generate the ID (which judging by your comment you did)
or set StoreGeneratedPattern property of OnlineCarStore.Models.ShoppingCarts Id column to 'None'
or use annotation: [DatabaseGenerated(DatabaseGeneratedOption.None)].

SQL Trigger on Insert to call a Function and Manipulate Values

I am having a problem knowing set up a trigger on insert to call a function and passing an identifier SiteID to that function which then operates on variables from another table.
I have the table, where values are inserted:
CREATE TABLE [dbo].[Tests] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[SiteID] NVARCHAR (128) NOT NULL,
[Date] NVARCHAR (MAX) NULL,
[Time] NVARCHAR (MAX) NULL,
[Tub] NVARCHAR (MAX) NULL,
[FCl] FLOAT (53) NOT NULL
PRIMARY KEY CLUSTERED ([Id] ASC)
);
Every time a value is inserted in to the Tests table I would like a function to be called which uses the table Review to perform a simple calculation (see the trigger down the post below):
CREATE TABLE [dbo].[Review] (
[SiteID] NVARCHAR (128) NOT NULL,
[TubNum] INT NOT NULL,
[Supplied] INT NULL,
[Performed] INT NULL,
[Remaining] INT NULL
PRIMARY KEY CLUSTERED ([SiteID] ASC)
);
This is my sqlfiddle so far, however, I am unable to save it with the functions I am working on, which are here:
The trigger - not sure how to pass the SiteID for the insert or call the function:
CREATE TRIGGER [dbo].[TRIG_MyTable]
ON [dbo].[Tests]
AFTER INSERT
AS
CALL CalcRemaining() //how to pass it SiteID?
and the the function itself:
CREATE FUNCTION [dbo].[CalcRemaining](#ID NVARCHAR (128))
RETURNS NULL
AS
BEGIN
SELECT (Supplied, Performed FROM Review WHERE SiteID = ID);
Performed = Performed + 1;
INSERT INTO Review (Performed, Remaining) VALUES (Performed, (Supplied-Performed))
RETURN;
END
The idea is that the SiteID from the inserted line is passed to the function when called, the function then selects the values Supplied and Performed for that matching SiteID from the Review table. The Performed value is incremented by 1 and that new value along with the retrieved Supplied value are subtracted and written to the Remaining field in the Review table.
If the assumptions I've asked about in the comments are valid (that Remaining and Performed can always be calculated), here's how I'd implement your database structure, with no trigger nor function:
Base tables:
CREATE TABLE dbo.Tests (
[Id] INT IDENTITY (1, 1) NOT NULL,
[SiteID] NVARCHAR (128) NOT NULL,
[Date] NVARCHAR (MAX) NULL,
[Time] NVARCHAR (MAX) NULL,
[Tub] NVARCHAR (MAX) NULL,
[FCl] FLOAT (53) NOT NULL
PRIMARY KEY CLUSTERED ([Id] ASC)
);
GO
CREATE TABLE dbo._Review (
[SiteID] NVARCHAR (128) NOT NULL,
[TubNum] INT NOT NULL,
[Supplied] INT NULL,
PRIMARY KEY CLUSTERED ([SiteID] ASC)
);
Then a view that calculates Performed:
CREATE VIEW dbo._Tests_Count
WITH SCHEMABINDING
AS
SELECT
SiteID,
COUNT_BIG(*) as Performed
FROM
dbo.Tests t
GROUP BY SiteID
GO
CREATE UNIQUE CLUSTERED INDEX IX_Tests_Count ON dbo._Tests_Count (SiteID)
And finally a view that re-creates the original Review table:
CREATE VIEW dbo.Review
WITH SCHEMABINDING
AS
SELECT
r.SiteID,
r.TubNum,
r.Supplied,
COALESCE(tc.Performed,0) as Performed,
r.Supplied - COALESCE(tc.Performed,0) as Remaining
FROM
dbo._Review r
left join
dbo._Tests_Count tc WITH (NOEXPAND)
on
r.SiteID = tc.SiteID
GO
If needed, at this point a trigger could be created on this Review view to allow any INSERTs, DELETEs and UPDATEs to be performed against it rather than _Review, if you cannot change some calling code.
You have to be completely sure you're manipulating ONLY one row at a time!
CREATE TRIGGER [dbo].[TRIG_MyTable]
ON [dbo].[Tests]
AFTER INSERT
AS
DECLARE #SiteID NVARCHAR (128)
SELECT #SiteID = ID FROM inserted
CALL CalcRemaining(#SiteID)