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
Related
I am using SQL server 2008 r2.
I was creating a table implicitly i.e without writing queries and tried to add primary key to one of the column by right clicking and selecting primary key.
But i could not add the primary key as it was not reflected there, i refreshed the table , the database and also closed the connection and re-connected but primary key was still not reflected on that column name. I tried this thrice.
Then I added primary key using query (Table was empty)
alter table [Table Name]
Add Primary key ([column name])
and then it got reflected in the table.
I tried searching for reason but could not find any convincing reason.
If anybody knows reason for this please reply.
ALTER TABLE [TableName]
ADD CONSTRAINT [PrimaryKeyName] PRIMARY KEY CLUSTERED ([ExistingColumn])
Make sure the column is NOT NULL i.e doesnt allow NULL values to be inserted.
Please check that you have "UNCHECKED" checkbox which says Prevent saving changes that require the table re-creation. You can follow below instruction to uncheck it.
Open SQL Server Management Studio (SSMS).
On the Tools menu, click Options.
In the navigation pane of the Options window, click Designers.
Select or clear the Prevent saving changes that require the table
re-creation check box, and then click OK.
I am using SQL Server 2012 and need to add a column with a unique primary key. I am about to load several hundred thousand records BULK and just discovered repetition in the field I was going to use. Have seen SEQUENCE and GUID. Need some guidance on the best choice and how to go about setting this up so that the key field is populated during the bulk load.
When you create your table in which you want to insert information create an IDENTITY column. That will serve as an auto-populating column with a unique number for each record.
Here is a link that might help you.
If you have already created your table just change this query to what suits to your table name and run it in order to add the new column you requested.
ALTER TABLE mytable
ADD COLUMN unique_id IDENTITY (1,1)
Just a slight update on what’s already posted that includes details for adding primary key constraint
alter table database.schema.table_t
add ID_column int identity(1,1)
primary key (ID_column)
If you already set the primary key on this table just go and remove it before you execute this statement.
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.
I have created a table with employee id as identity column. Now, I want to remove identity and replace datatype as bigint. I am using Sql Compact edition. How to achieve this?
I don't believe you can, using TSQL, remove the IDENTITY property from a column.
Instead:
Add a new BIGINT column to the table
Copy the data from the current IDENTITY field into the new field
Drop the existing column
Rename the new column to the correct name
You can do it in SSMS in the Design view for the table. I believe behind the scenes it does something like above.
Update:
To confirm, in SSMS 2K8 when you try to remove the IDENTITY property from a column and then save it, it will actually recreate the table (you can see what it does exactly by monitoring in SQL Profiler). In order to do it in SSMS, you need to ensure you have the "Prevent saving changes that require table re-creation" option turned OFF in Tools-> Options -> Designers -> Table and Database Designers. I think it defaults to ON, which would result in an error message when you try to do it otherwise.
In "real" SQL Server, you'd have to do these steps - not sure if SQL Server CE allows the same, but give it a try! I'm assuming you probably have your PRIMARY KEY constraint on that column, too - right? If not, you don't need to do the first and last step. And I'm assuming you want to have the IDENTITY on the column again, right?
-- DROP the primary key constraint (if you have that on your column)
ALTER TABLE dbo.Employees
DROP CONSTRAINT PK__Employees__3214EC274222D4EF
-- ALTER the datatype into BIGINT
ALTER TABLE dbo.Employees
ALTER COLUMN Employee_ID BIGINT
-- set PK constraint again
ALTER TABLE dbo.Employees
ADD CONSTRAINT PK_Employees PRIMARY KEY(Employee_ID)
This should help - http://www.sqlmag.com/Files/23/22081/Listing_03.txt
In all my searching I see that you essentially have to copy the existing table to a new table to chance to identity column for pre-2008, does this apply to 2008 also?
thanks.
most concise solution I have found so far:
CREATE TABLE Test
(
id int identity(1,1),
somecolumn varchar(10)
);
INSERT INTO Test VALUES ('Hello');
INSERT INTO Test VALUES ('World');
-- copy the table. use same schema, but no identity
CREATE TABLE Test2
(
id int NOT NULL,
somecolumn varchar(10)
);
ALTER TABLE Test SWITCH TO Test2;
-- drop the original (now empty) table
DROP TABLE Test;
-- rename new table to old table's name
EXEC sp_rename 'Test2','Test';
-- see same records
SELECT * FROM Test;
we cannot add identity to an existing column using sql command but we can do it using GUI.
Right click on the table - design - select the column on which you want to add identity.
go to the properties available below. find the identity specification and set it to yes.
save the table.
if it is not saved the go to tools from the menu - options - table designer - uncheck the checkbox prevent saving changes. now you can save the table modifications.
now your existing table had identity.
In all of the new feature documents I read about 2008, adding identity to an existing column was not a feature I recall. The solution you've found is correct and I think the process of adding identity increment to a column automatically would be only rarely useful.
Well you can do something like this.
ALTER TABLE my_table ADD ID_COLUMN INT IDENTITY (1,1) NOT NULL
You can add the IDENTITY property to an existing column using the GUI of Enterprise Manager / Management Studio.
In SQL 2005 and earlier, you could not modify an existing column to become an identity column. I deem it very very unlikely that MS changed that in 2008.