how to set auto increment column with sql developer - database

How do I set a column to increment automatically with Oracle SQL Developer? Why is the form disabled?
Note: The image shows the Data Modeler, but the question and top answer talk about editing an existing database.

If you want to make your PK auto increment, you need to set the ID column property for that primary key.
Right click on the table and select "Edit".
In "Edit" Table window, select "columns", and then select your PK
column.
Go to ID Column tab and select Column Sequence as Type. This will
create a trigger and a sequence, and associate the sequence to
primary key.
See the picture below for better understanding.
// My source is: http://techatplay.wordpress.com/2013/11/22/oracle-sql-developer-create-auto-incrementing-primary-key/

Unfortunately oracle doesnot support auto_increment like mysql does. You need to put a little extra effort to get that.
say this is your table -
CREATE TABLE MYTABLE (
ID NUMBER NOT NULL,
NAME VARCHAR2(100)
CONSTRAINT "PK1" PRIMARY KEY (ID)
);
You will need to create a sequence -
CREATE SEQUENCE S_MYTABLE
START WITH 1
INCREMENT BY 1
CACHE 10;
and a trigger -
CREATE OR REPLACE TRIGGER T_MYTABLE_ID
BEFORE INSERT
ON MYTABLE
REFERENCING NEW AS NEW
FOR EACH ROW
BEGIN
if(:new.ID is null) then
SELECT S_MYTABLE.nextval
INTO :new.ID
FROM dual;
end if;
END;
/
ALTER TRIGGER "T_MYTABLE_ID" ENABLE;

You can make auto increment in SQL Modeler. In column properties window Click : General then Tick the box of Auto Increment. After that the auto increment window will be enabled for you.

UPDATE: In Oracle 12c onward we have an option to create auto increment field, its better than trigger and sequence.
Right click on the table and select "Edit".
In "Edit" Table window, select "columns", and then select your PK
column.
Go to Identity Column tab and select "Generated as Identity" as Type, put 1 in both start with and increment field. This will
make this column auto increment.
See the below image
From SQL Statement
IDENTITY column is now available on Oracle 12c:
create table t1 (
c1 NUMBER GENERATED by default on null as IDENTITY,
c2 VARCHAR2(10)
);
or specify starting and increment values, also preventing any insert into the identity column (GENERATED ALWAYS) (again, Oracle 12c+ only)
create table t1 (
c1 NUMBER GENERATED ALWAYS as IDENTITY(START with 1 INCREMENT by 1),
c2 VARCHAR2(10)
);
EDIT : if you face any error like "ORA-30673: column to be modified is not an identity column", then you need to create new column and delete the old one.

#tom-studee you were right, it's possible to do it in the data modeler.
Double click your table, then go to the column section. Here double click on the column which will have the auto increment. In the general section there is a checkbox "autoincrement", just tick it.
After that you can also go to the "autoincrement" section to customize it.
When you save it and ask the data modeler to generate the SQL script, you will see the sequence and trigger which represent your autoincrement.

I found this post, which looks a bit old, but I figured I'd update everyone on my new findings.
I am using Oracle SQL Developer 4.0.2.15 on Windows.
Our database is Oracle 10g (version 10.2.0.1) running on Windows.
To make a column auto-increment in Oracle -
Open up the database connection in the Connections tab
Expand the Tables section, and right click the table that has the column you want to change to auto-increment, and select Edit...
Choose the Columns section, and select the column you want to auto-increment (Primary Key column)
Next, click the "Identity Column" section below the list of columns, and change type from None to "Column Sequence"
Leave the default settings (or change the names of the sequence and trigger if you'd prefer) and then click OK
Your id column (primary key) will now auto-increment, but the sequence will be starting at 1.
If you need to increment the id to a certain point, you'll have to run a few alter statements against the sequence.
This post has some more details and how to overcome this.
I found the solution here

Oracle doesn't have autoincrementing columns. You need a sequence and a trigger. Here's a random blog post that explains how to do it: http://www.lifeaftercoffee.com/2006/02/17/how-to-create-auto-increment-columns-in-oracle/

How to do it with Oracle SQL Developer:
In the Left pane, under the connections you will find "Sequences", right click and select create a new sequence from the context sensitive pop up. Fill out the details: Schema name, sequence_name, properties(start with value, min value, max value, increment value etc.) and click ok. Assuming that you have a table with a key that uses this auto_increment, while inserting in this table just give "your_sequence_name.nextval" in the field that utilizes this property.
I guess this should help! :)

Drag and drop your table from the left side menu into a worksheet and you will get a list of options. Pick "Insert" and then apply, and then done.

Related

Resetting the primary key to 1

I have a script for microsoft sql server database which has hundreds of tables and tables contains data as well. This is the database of a web application.what I want to do is to delete the previous records and reset the primary key to 1 or 0.
I have tried
`DBCC CHECKIDENT ('dbo.tbl',RESEED,0); `
but it does not work for me as in most of the tables the primary key is not identity.
I can not truncate the table as its primary key is being used as FK in many other tables.
I have also tried to add the identity specification in the primary key of the table and run the checkident query and then changing it back to non-identity spec, but after adding the record again it starts from where it left.
Making changes in the code is not an option for me.
please help.
According with your question I am not sure about the main objective, Why? If you need truncate a lot of tables and change their structures to have an Identity property why you can't disabled the FK? . In the past I have used an standard process for rebuild a table and migrate all the information, this represent a group of steps, I would try to help you but you should follow the next steps.
Steps:
1) Disable FK for alter the structure of your tables. You can get the solution for this task in the next link:
Temporarily disable all foreign key constraints
2) Alter the table with the new property Identity, this is a classic process of ALTER TABLE xxxxxx.
3) Execute the syntax that previously posted :
DBCC CHECKIDENT ('dbo.tbl',RESEED,0);
Try to follow this path and if you have any problem only ask us.
You can not truncate table that have relation. You shoud remove relation firstly.
My understanding of this question:
You have a database with tables that you want to empty and next have them use primary key values starting at 0 or 1.
Some of these tables use an identity value and you already have a solution for those (you know you can find out which columns have an identity by using the sys.columns view? Look for the is_identity column).
Some tables do not use an identity but get their pk values from an unknown source, which we can't modify.
The only solution I see, is creating an after insert trigger (or modifying) on those tables that subtracts from the new pk value.
E.g.: your "hidden generator" will generate a next value 5254, but you want the next pk value to become one:
CREATE TRIGGER trg_sometable_ai
ON sometable
AFTER INSERT
AS
BEGIN
UPDATE st
SET st.pk_col = st.pk_col - 5253
FROM sometable AS st
INNER JOIN INSERTED AS i
ON i.pk_col = th.pk_col
END
You'll have to determine the next value and thus the "subtract value" for each table.
If the code also inserts child records into tables with a foreign key to this table, and uses the previously generated value, you have to modify those triggers as well...
This is a "last resort" solution and something I would recommend against in any scenario that has other options. Manipulating primary key values is generally not a good idea.

Updating identity column in SQL Server and setting the seed starting value

I have a table filled with data and one of the columns - TrackingNumber - is an integer value. I have gotten a request to change it to auto-increment and to have it start the identity seed at 1000000. I know that I cannot alter a column to be an identity column in an existing table with data, so I have two options: either create an entirely new table and then move data from the old table into that new table or add an new identity column and update it with data from the old column.
The problem is that I need to retain all the existing values in column TrackingNumber. I have tried the following:
1) ALTER TABLE [dbo].[Table1]
ADD [TrackingNumber2] [bigint] IDENTITY (1000000, 1) NOT NULL
2) UPDATE [dbo].[Table1]
SET [TrackingNumber2]=[TrackingNumber]
3) ALTER TABLE [dbo].[Table1]
DROP COLUMN [TrackingNumber]
GO
4) EXEC sp_rename 'Table1.TrackingNumber2', 'TrackingNumber','COLUMN'
I got an error on step 2 - Updating new column with the value from the old column: "Cannot update identity column 'TrackingNumber2'"
Can anyone recommend a workaround?
You just need to set identity_insert on for this table so you can update the values. Make sure you turn it back off when you complete the update. :)
https://msdn.microsoft.com/en-us/library/ms188059.aspx
Are you sure you need to use an identity column? There are alternatives. For example, since SQL Server 2012 (and azure, too), there are these things called sequences. You can define a sequence to start at any number you like:
create sequence dbo.TrackingSequence
as int
start with 1000000
increment by 1
no maxvalue
no cycle
no cache
Then, you can alter the table such that the default value for the column in question defaults from the sequence:
alter table dbo.MyTable
add constraint [MyTable.TrackingNumber.Default.TrackingSequence]
default( next value for dbo.TrackingSequence ) for TrackingNumber
(If the column already has a default value, you need to remove that first - in a separate statement.)
A sequence works a lot like an identity, but you don't have to disrupt existing values or the column definition per se.
The only trick is to remember to not specify the value for TrackingNumber, and let the DB do its thing.
Sequences are cool in that you can have one sequence that is used by multiple tables, giving you somewhat shorter db-wide unique IDs than alternatives in the past. For such an application, you'd probably be better off with a bigint column - or know that the tables in question aren't going to be terribly long.
I ended up creating a new table and moving data in there

How To change the column order of An Existing Table in SQL Server 2008

I have situation where I need to change the order of the columns/adding new columns for existing Table in SQL Server 2008.
Existing column
MemberName
MemberAddress
Member_ID(pk)
and I want this order
Member_ID(pk)
MemberName
MemberAddress
I got the answer for the same ,
Go on SQL Server → Tools → Options → Designers → Table and Database Designers and unselect Prevent saving changes that require table re-creation
2- Open table design view and that scroll your column up and down and save your changes.
It is not possible with ALTER statement. If you wish to have the columns in a specific order, you will have to create a newtable, use INSERT INTO newtable (col-x,col-a,col-b) SELECT col-x,col-a,col-b FROM oldtable to transfer the data from the oldtable to the newtable, delete the oldtable and rename the newtable to the oldtable name.
This is not necessarily recommended because it does not matter which order the columns are in the database table. When you use a SELECT statement, you can name the columns and have them returned to you in the order that you desire.
If your table doesn't have any records you can just drop then create your table.
If it has records you can do it using your SQL Server Management Studio.
Just click your table > right click > click Design then you can now arrange the order of the columns by dragging the fields on the order that you want then click save.
Best Regards
I tried this and dont see any way of doing it.
here is my approach for it.
Right click on table and Script table for Create and have this on
one of the SQL Query window,
EXEC sp_rename 'Employee', 'Employee1' -- Original table name is Employee
Execute the Employee create script, make sure you arrange the columns in the way you need.
INSERT INTO TABLE2 SELECT * FROM TABLE1.
-- Insert into Employee select Name, Company from Employee1
DROP table Employee1.
Relying on column order is generally a bad idea in SQL. SQL is based on Relational theory where order is never guaranteed - by design. You should treat all your columns and rows as having no order and then change your queries to provide the correct results:
For Columns:
Try not to use SELECT *, but instead specify the order of columns in the select list as in: SELECT Member_ID, MemberName, MemberAddress from TableName. This will guarantee order and will ease maintenance if columns get added.
For Rows:
Row order in your result set is only guaranteed if you specify the ORDER BY clause.
If no ORDER BY clause is specified the result set may differ as the Query Plan might differ or the database pages might have changed.
Hope this helps...
This can be an issue when using Source Control and automated deployments to a shared development environment. Where I work we have a very large sample DB on our development tier to work with (a subset of our production data).
Recently I did some work to remove one column from a table and then add some extra ones on the end. I then had to undo my column removal so I re-added it on the end which means the table and all references are correct in the environment but the Source Control automated deployment will no longer work because it complains about the table definition changing.
The real problem here is that the table + indexes are ~120GB and the environment only has ~60GB free so I'll need to either:
a) Rename the existing columns which are in the wrong order, add new columns in the right order, update the data then drop the old columns
OR
b) Rename the table, create a new table with the correct order, insert to the new table from the old and delete from the old as I go along
The SSMS/TFS Schema compare option of using a temp table won't work because there isn't enough room on disc to do it.
I'm not trying to say this is the best way to go about things or that column order really matters, just that I have a scenario where it is an issue and I'm sharing the options I've thought of to fix the issue
SQL query to change the id column into first:
ALTER TABLE `student` CHANGE `id` `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT FIRST;
or by using:
ALTER TABLE `student` CHANGE `id` `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT AFTER 'column_name'

SQL Server - Autoincrementing on a generated table

Here's what I'm trying to do:
SELECT * INTO new_table FROM old_table WHERE 1=2;
ALTER TABLE new_table ADD CONSTRAINT pk_new_table_id PRIMARY KEY(id);
SET IDENTITY_INSERT new_table ON
Basically, I want to create a new table based on the structure of an existing one, then turn on autoincrementing for the ID field. However, when I try to insert rows I get this:
Table 'new_table ' does not have the identity property. Cannot perform SET operation.
Can anyone enlighten me as to what I'm doing wrong or how I should actually be going about this?
The table you create doesn't have an identity column. If you inspect the code you posted, you will notice that nowhere is an identity declared. I think you are confusing the concept of PRIMARY KEY and IDENTITY. They are distinct and unrelated. You cannot create a table with identity column using SELECT ... INTO ...
the column needs to be specified with " identity(1,1)" option. First 1 is the starting point and second is the increment.
set identity_insert on does not actually do what you think it does. It disables autoincrement (temporarily) so that you can hard code values in there.
Here's more info on that... http://msdn.microsoft.com/en-us/library/aa259221(v=sql.80).aspx
First, you have to create the new table without the use of "select ... into" and specify the column as an identity column.
Use the "set identity_insert .. on" before you copy the data over. Then, "set identity_insert ... off" when you're done.
If you want to cheat on the first part, you can use the management studio. Right click original table... goto the designer. Add identity option for the desired column. Then save off the script but do not commit. Might want to manipulate the newly generate script to create the new table. There are other more sophisticated solutions if you're going to have to do this repeatedly. But this by far is the simplest.
Here could be the problem:
ALTER TABLE new_table ADD CONSTRAINT pk_new_table_id PRIMARY KEY(id, idColumn);
Specify the id column.

Make a varchar(50) column unique

I have a column (which represents an e-mail) in a SQL Server database with varchar(50) as data type and I would like to make it unique (do not allow the same two e-mail addresses). I cannot find a way to make such column unique in SQL Server Management Studio.
How to do that?
In T-SQL it would be
ALTER TABLE MyTable WITH CHECK
ADD CONSTRAINT UQ_MyTable_Email UNIQUE (EmailAddress)
Or as an explicit index
CREATE UNIQUE INDEX IXU_Email ON MyTable (EmailAddress)
Edit: I can't see how to create a constraint in the SSMS GUI: other answers show how to manage indexes. I do only use SQL though, never the GUI for this kind of work
In the Object Explorer under the table right-click the Indexes folder and choose New Index....
In the window that appears enter Index name:, tick the Unique checkbox and add your email field from the Add... button then click OK.
Try this:
ALTER TABLE [dbo].[TableName] ADD CONSTRAINT UNQ__TableName__ColumnName UNIQUE ([ColumnName])
From this:
http://msdn.microsoft.com/en-us/library/ms191166.aspx

Resources