My question starts here: How to setup auto increment for Service-Based Database
So if I have to go this way to reset auto increment after deleting a table row:
http://befused.com/mysql/reset-auto-increment
first time I have deal with T-SQL extension and SQL generally. What is wrong here, not sure if I got it right:
CREATE TABLE [dbo].[Tab1] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Phrase] TEXT NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
SELECT MAX( Id ) FROM [Tab1] ;
ALTER TABLE Tab1 AUTO_INCREMENT = number;
got this errors:
Severity Code Description Project File Line Suppression State Error
SQL80001: Incorrect syntax near ''. Expecting '.', ID, or QUOTED_ID.
dbo.User 8
and:
SeverityCode Description Project File Line Suppression State Error
SQL80001: Incorrect syntax near ''. dbo.User 7
MYSQL
CREATE TABLE Tab1 (
Id INT NOT NULL AUTO_INCREMENT,
Phrase TEXT NOT NULL,
PRIMARY KEY CLUSTERED (Id ASC)
);
ALTER TABLE Tab1 MODIFY COLUMN Id INT AUTO_INCREMENT // To set column as auto increment
MSSQL (In case someone needs it)
The create table syntax is OK but in creating auto increment column, you can add it like this
CREATE TABLE [dbo].[User] (
[Id] INT NOT NULL AUTO_INCREMENT PRIMARY KEY, // Set column as primary key and auto increment
[Phrase] TEXT NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
SELECT MAX( Id ) FROM [User]; // You forgot the brackets in this part,Useris a reserved word in TSQL
If you want to reseed to different number you can use below:
dbcc checkident(tab1, reseed, 100)
Related
I am beginner in sql.I am using sqlplus to run the sql query .I used simple query but it shows an error like "MISSING RIGHT PARENTHESIS".My objective is to create the autoincrement primary key .Can anyone solve the error?Thanks in advance...
create table student(rollno int identity(1,1) primary key,
name varchar(20),marks int);
For Oracle, the rollno column could be defined as NUMBER(0010) and primary key.
Then you would need to add an ON INSERT trigger to populate rollno from a SEQUENCE. There are many samples of triggers and sequences on this site.
In oracle 12 you can use a identity column to automatically fill your ID
CREATE TABLE students
(
"ID" NUMBER GENERATED BY DEFAULT AS IDENTITY MINVALUE 1 MAXVALUE 9999999999
INCREMENT BY 1 START WITH 1 ,
"NAME" VARCHAR2(20),
"MARKS" NUMBER(2,0),
CONSTRAINT PK_STUDENTS PRIMARY KEY (ID) ENABLE
);
/
This creates a table without any triggers needed and automatically fills the id column (of not specified with a value) with the next number up to 99999...
If you're using oracle 11 and below, you need a trigger on insert and assign a value (custom_sequence.nextval) to the id column.
CREATE TABLE students
(
"ID" NUMBER(5,0) not null,
"NAME" VARCHAR2(20),
"MARKS" NUMBER(2,0),
CONSTRAINT PK_STUDENTS PRIMARY KEY (ID) ENABLE
);
/
CREATE SEQUENCE SEQ_STUDENTS INCREMENT BY 1 START WITH 1;
/
TRIGGER TC_students
before insert on students
for each row
begin
if (:new.id is null) then
select SEQ_students.nextval into :new.id from dual;
end if;
end;
/
And please use VARCHAR2.
My database is SQL Server. I want to insert a duplicate key in RequestId, then come across this error.
In addition:My database is created by Visual Studio Sql Server 2008 Server Project
I'm sure there is no constraint in the table.
Neither a column is PRIMARY KEY:
CREATE TABLE [dbo].[RequestPrize] (
[RequestId] INT NOT NULL,
[PrizeId] INT NULL,
[Verified] BIT NOT NULL,
[Created] SMALLDATETIME NOT NULL
);
But when I insert a duplicate key of RequestId:
insert into [RequestPrize] (RequestId, PrizeId) values('138', 9)
error output :
Violation of PRIMARY KEY constraint 'PK_RequestPrize'. Cannot insert duplicate key in object 'dbo.RequestPrize'.
Then I try to drop this constraint,
ALTER TABLE [RequestPrize] DROP CONSTRAINT RequestId
error :
Msg 3728, Level 16, State 1, Line 1
'RequestId' is not a constraint.
Msg 3727, Level 16, State 0, Line 1
Could not drop constraint. See previous errors.
update:
I really want to know where this CONSTRAINT come from.
Without PK all works fine -
CREATE TABLE dbo.RequestPrize
(
[RequestId] INT NOT NULL,
[PrizeId] INT NULL,
[Verified] BIT NOT NULL DEFAULT 0,
[Created] SMALLDATETIME NOT NULL DEFAULT GETDATE()
)
GO
INSERT INTO dbo.RequestPrize (RequestId, PrizeId)
VALUES (138, 9)
GO
INSERT INTO dbo.RequestPrize (RequestId, PrizeId)
VALUES (138, 9)
GO
So drop (if exist) your PK -
IF EXISTS(
SELECT 1
FROM sys.objects o
WHERE o.type = 'PK'
AND o.parent_object_id = OBJECT_ID('dbo.RequestPrize', 'U')
) ALTER TABLE dbo.RequestPrize DROP CONSTRAINT PK_RequestPrize
To drop a constraint you have to use the alias name for constraint you specified while creating "PK_RequestPrize".
By Syntax i guess you are using Microsoft SQLserver, to be sure check if query browser is connected to proper DB.
use "[dbo].[RequestPrize]" while inserting to have more confirmation.
When I try to run my app, I get the following errors:
There is already an object named 'PK_***' in the database. Could not create constraint."
That's actually two errors combined for brevity. Note: the asterisks are my own; that is not the actual name of the key.
I've scoured what seems like every post on here, but I can't seem to get any further in finding a solution. The worst part? No one else in the team is experiencing these errors when they run, nor can they determine why I am. We are all using the same environment, VS 2012 Premium RC. I certainly have latest from TFS.
I am wondering if anyone else has come across an issue similar to this where the problems/errors occurred in only one person's environment? I can continue and run the app. It seems to run as expected, but I am the only one getting those errors.
In SQL Server constraints such as primary keys or foreign keys are objects in their own right, even though they are dependent upon the "containing" table.
That means that their names must be unique within the owning schema. So, just as executing DDL along the lines of
create table some_schema.foo
(
id int not null
)
go
create table some_schema.foo
(
id int not null
)
go
will raise an error when the second create table is [attempted to be] executed, executing ddl like this will likewise raise an error:
create table some_schema.foo
(
id int not null ,
description varchar(200) not null ,
constraint PK primary key clustered ( id ) ,
constraint AK01 unique nonclustered ( description ) ,
)
go
create table some_schema.bar
(
id int not null ,
description varchar(200) not null ,
constraint PK primary key clustered ( id ) ,
constraint AK01 unique nonclustered ( description ) ,
)
go
will likewise raise an error as the constraint that you're trying to create have duplicate names. You need to qualify them with the table name, thusly:
create table some_schema.foo
(
id int not null ,
description varchar(200) not null ,
constraint foo_PK primary key clustered ( id ) ,
constraint foo_AK01 unique nonclustered ( description ) ,
)
go
create table some_schema.bar
(
id int not null ,
description varchar(200) not null ,
constraint bar_PK primary key clustered ( id ) ,
constraint bar_AK01 unique nonclustered ( description ) ,
)
go
and you problem will go away.
It does seem to me that dependent objects that don't exist outside the context of an owing object should be namespaced within the owning object's scope, but that's not the way the SQL standard works.
Good luck!
Using Postgres, I'm trying to use AUTO_INCREMENT to number my primary key automatically in SQL. However, it gives me an error.
CREATE TABLE Staff (
ID INTEGER NOT NULL AUTO_INCREMENT,
Name VARCHAR(40) NOT NULL,
PRIMARY KEY (ID)
);
The error:
********** Error **********
ERROR: syntax error at or near "AUTO_INCREMENT"
SQL state: 42601
Character: 63
Any idea why?
Postgres 10 or later
(serial columns remain unchanged, see below.)
Consider a standard-SQL IDENTITY column. Can be GENERATED BY DEFAULT or (stricter) GENERATED ALWAYS.
Basics in the manual for CREATE TABLE.
Details in this blog entry by its principal author Peter Eisentraut.
Create table with IDENTITY column
CREATE TABLE staff (
staff_id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY
, staff text NOT NULL
);
Add IDENTITY column to existing table
Table may or may not be populated with rows.
ALTER TABLE staff ADD COLUMN staff_id int GENERATED ALWAYS AS IDENTITY;
To also make it the PK at the same time (table can't have a PK yet):
ALTER TABLE staff ADD COLUMN staff_id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY;
See:
How to add a PostgreSQL 10 identity column to an existing table with rows?
Replace serial with IDENTITY column
See:
How to change a table ID from serial to identity?
You can override system values or user input in INSERT commands with OVERRIDING {SYSTEM|USER} VALUE.
Postgres 9.6 or older
(Still supported in newer versions, too.)
Use the serial pseudo data type:
CREATE TABLE staff (
staff_id serial PRIMARY KEY,
, staff text NOT NULL
);
It creates and attaches the sequence object automatically and sets the DEFAULT to nextval() from the sequence. It does all you need.
I use legal, lower-case, unquoted identifiers in my examples. Makes your life with Postgres easier.
You do not specify which RDBMS you are using, however, in SQL Server you can use this syntax:
CREATE TABLE [dbo].[Staff]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] VARCHAR(40) NOT NULL,
CONSTRAINT [ID] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
In the SQL server database you can use Identity(1,1) like this:
CREATE TABLE Staff
(
ID INT IDENTITY(1,1) NOT NULL,
Name VARCHAR(40) NOT NULL,
PRIMARY KEY (ID)
);
PostgreSQL: If you absolutely must have your own auto increment value:
Then use a sequence:
ericlesc_schools=> drop table yar;
DROP TABLE
ericlesc_schools=> drop sequence user_id_seq;
DROP SEQUENCE
ericlesc_schools=> create sequence user_id_seq;
CREATE SEQUENCE
ericlesc_schools=> create table yar(
id int default nextval('user_id_seq'),
foobar varchar);
CREATE TABLE
ericlesc_schools=> insert into yar (foobar) values('hey alex');
INSERT 0 1
ericlesc_schools=> insert into yar (foobar) values('hey what derick');
INSERT 0 1
ericlesc_schools=> insert into yar (foobar) values('I look like a hushpuppy');
INSERT 0 1
ericlesc_schools=> select * from yar;
id | foobar
----+-----------------
1 | hey alex
2 | hey what derick
3 | I look like a hushpuppy
(3 rows)
I have a table with the following definition:
CREATE TABLE url_tracker (
id int not null identity(1, 1),
active bit not null,
install_date int not null,
partner_url nvarchar(512) not null,
local_url nvarchar(512) not null,
public_url nvarchar(512) not null,
primary key(id)
);
And I have a requirement that these three URLs always be unique - any individual URL can appear many times, but the combination of the three must be unique (for a given day).
Initially I thought I could do this:
CREATE UNIQUE INDEX uniques ON url_tracker
(install_date, partner_url, local_url, public_url);
However this gives me back the warning:
Warning! The maximum key length is 900 bytes. The index 'uniques' has maximum
length of 3076 bytes. For some combination of large values, the insert/update
operation will fail.
Digging around I learned about the INCLUDE argument to CREATE INDEX, but according to this question converting the command to use INCLUDE will not enforce uniqueness on the URLs.
CREATE UNIQUE INDEX uniques ON url_tracker (install_date)
INCLUDE (partner_url, local_url, public_url);
How can I enforce uniqueness on several relatively large nvarchar fields?
Resolution
So from the comments and answers and more research I'm concluding I can do this:
CREATE TABLE url_tracker (
id int not null identity(1, 1),
active bit not null,
install_date int not null,
partner_url nvarchar(512) not null,
local_url nvarchar(512) not null,
public_url nvarchar(512) not null,
uniquehash AS HashBytes('SHA1',partner_url+local_url+public_url) PERSISTED,
primary key(id)
);
CREATE UNIQUE INDEX uniques ON url_tracker (install_date,uniquehash);
Thoughts?
I would make a computed column with the hash of the URLs, then make a unique index/constraint on that. Consider making the hash a persisted computed column. It shouldn't have to be recalculated after insertion.
Following the ideas from the conversation in the comments. Assuming that you can change the datatype of the URL to be VARCHAR(900) (or NVARCHAR(450) if you really think you need Unicode URLs) and be happy with the limitation on the length of the URL, this solution could work. This also assumes SQL Server 2008 or better. Please, always specify what version you're working with; sql-server is not specific enough, since solutions can vary greatly depending on the version.
Setup:
USE tempdb;
GO
CREATE TABLE dbo.urls
(
id INT IDENTITY(1,1) PRIMARY KEY,
url VARCHAR(900) NOT NULL UNIQUE
);
CREATE TABLE dbo.url_tracker
(
id INT IDENTITY(1,1) PRIMARY KEY,
active BIT NOT NULL DEFAULT 1,
install_date DATE NOT NULL DEFAULT CURRENT_TIMESTAMP,
partner_url_id INT NOT NULL REFERENCES dbo.urls(id),
local_url_id INT NOT NULL REFERENCES dbo.urls(id),
public_url_id INT NOT NULL REFERENCES dbo.urls(id),
CONSTRAINT unique_urls UNIQUE
(
install_date,partner_url_id, local_url_id, public_url_id
)
);
Insert some URLs:
INSERT dbo.urls(url) VALUES
('http://msn.com/'),
('http://aol.com/'),
('http://yahoo.com/'),
('http://google.com/'),
('http://gmail.com/'),
('http://stackoverflow.com/');
Now let's insert some data:
-- succeeds:
INSERT dbo.url_tracker(partner_url_id, local_url_id, public_url_id)
VALUES (1,2,3), (2,3,4), (3,4,5), (4,5,6);
-- fails:
INSERT dbo.url_tracker(partner_url_id, local_url_id, public_url_id)
VALUES(1,2,3);
GO
/*
Msg 2627, Level 14, State 1, Line 3
Violation of UNIQUE KEY constraint 'unique_urls'. Cannot insert duplicate key
in object 'dbo.url_tracker'. The duplicate key value is (2011-09-15, 1, 2, 3).
The statement has been terminated.
*/
-- succeeds, since it's for a different day:
INSERT dbo.url_tracker(install_date, partner_url_id, local_url_id, public_url_id)
VALUES('2011-09-01',1,2,3);
Cleanup:
DROP TABLE dbo.url_tracker, dbo.urls;
Now, if 900 bytes is not enough, you could change the URL table slightly:
CREATE TABLE dbo.urls
(
id INT IDENTITY(1,1) PRIMARY KEY,
url VARCHAR(2048) NOT NULL,
url_hash AS CONVERT(VARBINARY(32), HASHBYTES('SHA1', url)) PERSISTED,
CONSTRAINT unique_url UNIQUE(url_hash)
);
The rest doesn't have to change. And if you try to insert the same URL twice, you get a similar violation, e.g.
INSERT dbo.urls(url) SELECT 'http://www.google.com/';
GO
INSERT dbo.urls(url) SELECT 'http://www.google.com/';
GO
/*
Msg 2627, Level 14, State 1, Line 1
Violation of UNIQUE KEY constraint 'unique_url'. Cannot insert duplicate key
in object 'dbo.urls'. The duplicate key value is
(0xd111175e022c19f447895ad6b72ff259552d1b38).
The statement has been terminated.
*/