I have created one table in PL SQL Developer.
CREATE TABLE Patient_List
(
Patient_ID number NOT NULL,
Patient_Name varchar(50) NOT NULL,
Patient_Address varchar(100) NULL,
App_Date date NULL,
Descr varchar(50),
CONSTRAINT patient_pk PRIMARY KEY(Patient_ID)
);
I want to auto increment Patient_ID, I tried altering the table and modifying the Patient_ID column but it's showing an error "invalid ALTER TABLE option"
ALTER TABLE Patient_List
MODIFY Patient_ID NUMBER NOT NULL GENERATED ALWAYS AS IDENTITY;
Please help, Thanks in advance.
This is not possible.
Oracle 10g didn't even have identity columns, they were introduced in Oracle 12.1
But even with a current Oracle version, you can't convert a regular column to an identity column. You would need to add a new one.
Before identity columns, the usual way was to create a sequence and a trigger to populate the column.
See here: How to create id with AUTO_INCREMENT on Oracle?
If anybody wants to modify existing column as auto_increment use this three lines
alter table Product drop column test_id;
create sequence Product_test_id_seq INCREMENT BY 1 nocache;
alter table Product add test_id Number default Product_test_id_seq.nextval not null;
Related
I have a table viz. expenses with three columns as under
ExpenseId int NOT NULL,
ExpenseName varchar(50) NOT NULL,
Invalid bit NOT NULL
To add a new column (OldCode char(4) not null), I used design feature for tables in Microsoft SQL Server Management Studio. But I get following error
'Expenses' table
- Unable to modify table. Cannot insert the value NULL into column 'OldCode', table 'TransportSystemMaster.dbo.Tmp_Expenses'; column does not allow nulls. INSERT fails. The statement has been terminated.
Incidentally I have been able to add same column with same specifications to other tables of the same database.
Any help?
Your Table Consist of Existing Records
and you are pushing a new column of type NOT NULL.
so for older records the data have to be something.
try something like this
ALTER TABLE MY_TABLE ADD Column_name INT NULL
GO
UPDATE MY_TABLE <set valid not null values for your column>
GO
ALTER TABLE MY_TABLE ALTER COLUMN Column_name INT NOT NULL
GO
Since OldCode is NOT NULL, you should specify a default value for it.
when you have some rows on your table you can't add a column that is not nullable you should provide a default value for it
Alter Table table_name add OldCode int not null DEFAULT(0);
You have to specify values for all the 4 fields of the table, its purely because, while designing the table you set the definition of the columns to be not null. Again you are adding a new column called OldCode and setting to be not null, all ready existing records hasn't got a value. So that is the reason its complains
I have like 11 columns in my database table and i am inserting data in 10 of them. i want to have a unique number like "1101 and so on" in the 11th column.
Any idea what should i do?? Thanks in advance.
SQL Server 2012 and above you can generate Sequence
Create SEQUENCE RandomSeq
start with 1001
increment by 1
Go
Insert into YourTable(Id,col1...)
Select NEXT VALUE FOR RandomSeq,col1....
or else you can use Identity
Identity(seed,increment)
You can start the seed from 1101 and increment the sequence by 1
Create table YourTable
(
id INT IDENTITY(1101,1),
Col varchar(10)
)
If you want to have that unique number in a different field then you can manipulate that field with primary key and insert that value.
If you want in primary key value, then open the table in design mode, go to 'Identity specification', set 'identity increment' and 'identity seed' as you want.
Alternatively you can use table script like,
CREATE TABLE Persons
(
ID int IDENTITY(12,1) PRIMARY KEY,
FName varchar(255) NOT NULL,
)
here the primary key will start seeding from 12 and seed value will be 1.
If you have your table definition already in place you can alter the column and add Computed column marked as persisted as:
ALTER TABLE tablename drop column column11;
ALTER TABLE tablename add column11 as '11'
+right('000000'+cast(ID as varchar(10)), 2) PERSISTED ;
--You can change the right operator value from 2 to any as per the requirements.
--Also replace ID with the identity column in your table.
create table inc
(
id int identity(1100,1),
somec char
)
In PostgreSql, one can define a sequence and use it as the primary key of a table. In HsqlDB, one can still accomplish creating an auto-increment identity column which doesn't link to any user defined sequence. Is it possible to use a user defined sequence as the generator of an auto-increment identity column in HsqlDB?
Sample sql in PostgreSql:
CREATE SEQUENCE seq_company_id START WITH 1;
CREATE TABLE company (
id bigint PRIMARY KEY DEFAULT nextval('seq_company_id'),
name varchar(128) NOT NULL CHECK (name <> '')
);
What's the equivalent in HsqlDB?
Thanks.
In version 2.0, there is no direct feature for this. You can define a BEFORE INSERT trigger on the table to do this:
CREATE TABLE company ( id bigint PRIMARY KEY, name varchar(128) NOT NULL CHECK (name <> '') );
CREATE TRIGGER trigg BEFORE INSERT
ON company REFERENCING NEW ROW AS newrow
FOR EACH ROW
SET newrow.id = NEXT VALUE FOR seq_company_id;
and insert without using any vlue for id
INSERT INTO company VALUES null, 'test'
Update for HSQLDB 2.1 and later: A feature has been added to support this.
CREATE SEQUENCE SEQU
CREATE TABLE company ( id bigint GENERATED BY DEFAULT AS SEQUENCE SEQU PRIMARY KEY, name varchar(128) NOT NULL CHECK (name <> '') );
See the Guide under CREATE TABLE http://hsqldb.org/doc/2.0/guide/databaseobjects-chapt.html#dbc_table_creation
In addition, 2.1 and later has a PostgreSQL compatibility mode in which it accepts the PostgreSQL CREATE TABLE statement that references the sequence in the DEFAULT clause and translates it to HSQLDB syntax.
I’m trying to modify a table to make its primary key column AUTO_INCREMENT after the fact. I have tried the following SQL, but got a syntax error notification.
ALTER TABLE document
ALTER COLUMN document_id AUTO_INCREMENT
Am I doing something wrong or is this not possible?
+--------------------+
| VERSION() |
+--------------------+
| 5.0.75-0ubuntu10.2 |
+--------------------+
ALTER TABLE document MODIFY COLUMN document_id INT auto_increment
Roman is right, but note that the auto_increment column must be part of the PRIMARY KEY or a UNIQUE KEY (and in almost 100% of the cases, it should be the only column that makes up the PRIMARY KEY):
ALTER TABLE document MODIFY document_id INT AUTO_INCREMENT PRIMARY KEY
In my case it only worked when I put not null. I think this is a constraint.
ALTER TABLE document MODIFY COLUMN document_id INT NOT NULL AUTO_INCREMENT;
You can apply the atuto_increment constraint to the data column by the following query:
ALTER TABLE customers MODIFY COLUMN customer_id BIGINT NOT NULL AUTO_INCREMENT;
But, if the columns are part of a foreign key constraint you, will most probably receive an error. Therefore, it is advised to turn off foreign_key_checks by using the following query:
SET foreign_key_checks = 0;
Therefore, use the following query instead:
SET foreign_key_checks = 0;
ALTER TABLE customers MODIFY COLUMN customer_id BIGINT NOT NULL AUTO_INCREMENT;
SET foreign_key_checks = 1;
The SQL to do this would be:
ALTER TABLE `document` MODIFY COLUMN `document_id` INT AUTO_INCREMENT;
There are a couple of reasons that your SQL might not work. First, you must re-specify the data type (INT in this case). Also, the column you are trying to alter must be indexed (it does not have to be the primary key, but usually that is what you would want). Furthermore, there can only be one AUTO_INCREMENT column for each table. So, you may wish to run the following SQL (if your column is not indexed):
ALTER TABLE `document` MODIFY `document_id` INT AUTO_INCREMENT PRIMARY KEY;
You can find more information in the MySQL documentation: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html for the modify column syntax and http://dev.mysql.com/doc/refman/5.1/en/create-table.html for more information about specifying columns.
You must specify the type of the column before the auto_increment directive, i.e. ALTER TABLE document MODIFY COLUMN document_id INT AUTO_INCREMENT.
AUTO_INCREMENT is part of the column's datatype, you have to define the complete datatype for the column again:
ALTER TABLE document
ALTER COLUMN document_id int AUTO_INCREMENT
(int taken as an example, you should set it to the type the column had before)
You can do it like this:
alter table [table_name] modify column [column_name] [column_type] AUTO_INCREMENT;
You can use the following query to make document_id to increment automatically
ALTER TABLE document MODIFY COLUMN document_id INT auto_increment
It is preferred to make document_id primary key as well
ALTER TABLE document MODIFY COLUMN document_id INT auto_increment PRIMARY KEY;
Below statement works. Note that you need to mention the data type again for the column name (redeclare the data type the column was before).
ALTER TABLE document
MODIFY COLUMN document_id int AUTO_INCREMENT;
AUTO_INCREMENT is part of the column's datatype, you have to define the complete datatype for the column again:
ALTER TABLE document
MODIFY COLUMN document_id int AUTO_INCREMENT
(int taken as an example, you should set it to the type the column had before)
If none of the above works try this. This is what I did in MYSQL and yes, you need to write the column name (document_id) twice.
ALTER TABLE document
CHANGE COLUMN document_id document_id INT(11) NOT NULL AUTO_INCREMENT ;
Setting column as primary key and auto_increment at the same time:
mysql> ALTER TABLE persons MODIFY COLUMN personID INT auto_increment PRIMARY KEY;
Query OK, 10 rows affected (0.77 sec)
Records: 10 Duplicates: 0 Warnings: 0
mysql>
To modify the column in mysql we use alter and modify keywords. Suppose we have created a table like:
create table emp(
id varchar(20),
ename varchar(20),
salary float
);
Now we want to modify type of the column id to integer with auto increment. You could do this with a command like:
alter table emp modify column id int(10) auto_increment;
Previous Table syntax:
CREATE TABLE apim_log_request (TransactionId varchar(50) DEFAULT NULL);
For changing the TransactionId to auto increment use this query
ALTER TABLE apim_log_request MODIFY COLUMN TransactionId INT auto_increment;
alter table tbl_user MODIFY COLUMN id int(10) auto_increment;
Just like this:
alter table document modify column id int(11) auto_increment;
As you are redefining the column again, you have to specify the datatype again and add auto_increment to it as it's a part of datatype.
ALTER TABLE `document` MODIFY COLUMN `document_id` INT AUTO_INCREMENT;
Try the following:
ALTER TABLE table_name MODIFY COLUMN id datatype auto_increment;
Since SQL tag is attached to the question I really think all answers missed one major point.
MODIFY command does not exist in SQL server So you will be getting an error when you run the
ALTER TABLE Satellites MODIFY COLUMN SatelliteID INT auto_increment PRIMARY KEY;
In this case you can either add new column as INT IDENTITY
ALTER TABLE Satellites
ADD ID INT IDENTITY
CONSTRAINT PK_YourTable PRIMARY KEY CLUSTERED;
OR
Fill the existing null index with incremental numbers using this method,
DECLARE #id INT
SET #id = 0
UPDATE Satellites SET #id = SatelliteID = #id + 1
Use the following queries:
ALTER TABLE YourTable DROP COLUMN IDCol
ALTER TABLE YourTable ADD IDCol INT IDENTITY(1,1)
I need to have one column as the primary key and another to auto increment an order number field. Is this possible?
EDIT: I think I'll just use a composite number as the order number. Thanks anyways.
CREATE TABLE [dbo].[Foo](
[FooId] [int] IDENTITY(1,1) NOT NULL,
[BarId] [int] IDENTITY(1,1) NOT NULL
)
returns
Msg 2744, Level 16, State 2, Line 1
Multiple identity columns specified for table 'Foo'. Only one identity column per table is allowed.
So, no, you can't have two identity columns. You can of course make the primary key not auto increment (identity).
Edit: msdn:CREATE TABLE (Transact-SQL) and CREATE TABLE (SQL Server 2000):
Only one identity column can be created per table.
You can use Sequence for second column with default value IF you use SQL Server 2012
--Create the Test schema
CREATE SCHEMA Test ;
GO
-- Create a sequence
CREATE SEQUENCE Test.SORT_ID_seq
START WITH 1
INCREMENT BY 1 ;
GO
-- Create a table
CREATE TABLE Test.Foo
(PK_ID int IDENTITY (1,1) PRIMARY KEY,
SORT_ID int not null DEFAULT (NEXT VALUE FOR Test.SORT_ID_seq));
GO
INSERT INTO Test.Foo VALUES ( DEFAULT )
INSERT INTO Test.Foo VALUES ( DEFAULT )
INSERT INTO Test.Foo VALUES ( DEFAULT )
SELECT * FROM Test.Foo
-- Cleanup
--DROP TABLE Test.Foo
--DROP SEQUENCE Test.SORT_ID_seq
--DROP SCHEMA Test
http://technet.microsoft.com/en-us/library/ff878058.aspx
Add one identity column and then add a computed column whose formula is the name of the identity column
Now both will increment at the same time
No it is not possible to have more than one identity column.
The Enterprise Manager does not even allow you to set > 1 column as identity. When a second column is made identity
Also note that ##identity returns the last identity value for the open connection which would be meaningless if more than one identity column was possible for a table.
create table #tblStudent
(
ID int primary key identity(1,1),
Number UNIQUEIDENTIFIER DEFAULT NEWID(),
Name nvarchar(50)
)
Two identity column is not possible but if you accept to use a unique identifier column then this code does the same job as well. And also you need an extra column - Name column- for inserting values.
Example usage:
insert into #tblStudent(Name) values('Ali')
select * from #tblStudent
Ps: NewID() function creates a unique value of type uniqueidentifier.
The primary key doesn't need to be an identity column.
You can't have two Identity columns.
You could get something close to what you want with a trigger...
in sql server it's not possible to have more than one column as identity.
I've just created a code that will allow you inserting two identities on the same table. let me share it with you in case it helps:
create trigger UpdateSecondTableIdentity
On TableName For INSERT
as
update TableName
set SecondIdentityColumn = 1000000+##IDENTITY
where ForstId = ##IDENTITY;
Thanks,
A workaround would be to create an INSERT Trigger that increments a counter.
So I have a table that has one identity col : applicationstatusid. its also the primary key.
I want to auto increment another col: applicationnumber
So this is the trigger I write.
create trigger [applicationstatus_insert] on [ApplicationStatus] after insert as
update [Applicationstatus]
set [Applicationstatus].applicationnumber =(applicationstatusid+ 4000000)
from [Applicationstatus]
inner join inserted on [applicationstatus].applicationstatusid = inserted.applicationstatusid