SQL Server 2005 How Create a Unique Constraint? - sql

How do I create a unique constraint on an existing table in SQL Server 2005?
I am looking for both the TSQL and how to do it in the Database Diagram.

The SQL command is:
ALTER TABLE <tablename> ADD CONSTRAINT
<constraintname> UNIQUE NONCLUSTERED
(
<columnname>
)
See the full syntax here.
If you want to do it from a Database Diagram:
right-click on the table and select 'Indexes/Keys'
click the Add button to add a new index
enter the necessary info in the Properties on the right hand side:
the columns you want (click the ellipsis button to select)
set Is Unique to Yes
give it an appropriate name

In SQL Server Management Studio Express:
Right-click table, choose Modify or Design(For Later Versions)
Right-click field, choose Indexes/Keys...
Click Add
For Columns, select the field name you want to be unique.
For Type, choose Unique Key.
Click Close, Save the table.

ALTER TABLE [TableName] ADD CONSTRAINT [constraintName] UNIQUE ([columns])

Warning: Only one null row can be in the column you've set to be unique.
You can do this with a filtered index in SQL 2008:
CREATE UNIQUE NONCLUSTERED INDEX idx_col1
ON dbo.MyTable(col1)
WHERE col1 IS NOT NULL;
See Field value must be unique unless it is NULL for a range of answers.

ALTER TABLE dbo.<tablename> ADD CONSTRAINT
<namingconventionconstraint> UNIQUE NONCLUSTERED
(
<columnname>
) ON [PRIMARY]

I also found you can do this via, the database diagrams.
By right clicking the table and selecting Indexes/Keys...
Click the 'Add' button, and change the columns to the column(s) you wish make unique.
Change Is Unique to Yes.
Click close and save the diagram, and it will add it to the table.

You are looking for something like the following
ALTER TABLE dbo.doc_exz
ADD CONSTRAINT col_b_def
UNIQUE column_b
MSDN Docs

To create a UNIQUE constraint on one or multiple columns when the table is already created, use the following SQL:
ALTER TABLE TableName ADd UNIQUE (ColumnName1,ColumnName2, ColumnName3, ...)
To allow naming of a UNIQUE constraint for above query
ALTER TABLE TableName ADD CONSTRAINT un_constaint_name UNIQUE (ColumnName1,ColumnName2, ColumnName3, ...)
The query supported by MySQL / SQL Server / Oracle / MS Access.

In the management studio diagram choose the table, right click to add new column if desired, right-click on the column and choose "Check Constraints", there you can add one.

In some situations, it could be desirable to ensure the Unique key does not exists before create it. In such cases, the script below might help:
IF Exists(SELECT * FROM sys.indexes WHERE name Like '<index_name>')
ALTER TABLE dbo.<target_table_name> DROP CONSTRAINT <index_name>
GO
ALTER TABLE dbo.<target_table_name> ADD CONSTRAINT <index_name> UNIQUE NONCLUSTERED (<col_1>, <col_2>, ..., <col_n>)
GO

Related

a set of column to be unique key in sql database

How can I make a set of column to be unique key in sql server database?
for example: I have a database that have just one table by columns 1_book 2_page 3_line 4_word i want to search a word in some books and record this information .
where is the problem? if it find a words twice or more in a line it will save the same record to table.it is not important for me how many times a word is repeated in a line. i want if a word to be repeated once or more save the information.
is there any way to say every record should be unique?
searching a record in table before Inserting it to table is not reasonable .isn't it?
Just create a unique constraint for your table: (example for ms sql-server)
ALTER TABLE <yourtablename> ADD CONSTRAINT
UniqueEntries UNIQUE NONCLUSTERED
(
1_book, 2_page, 3_line, 4_word
)
If you do not want to get errors and simply ignore additional adds of the same word in the same line, you can extend the constraint with IGNORE_DUP_KEY = ON
Example:
ALTER TABLE <yourtablename> ADD CONSTRAINT
UniqueEntries UNIQUE NONCLUSTERED
(
1_book, 2_page, 3_line, 4_word
) WITH (IGNORE_DUP_KEY = ON)
Inserts with already existing records will then just be silently ignored.
You mean, you don't know how to create composite keys? Well:
alter table dbo.Words add constraint PK_Words primary key (
1_book, 2_page, 3_line, 4_word
);
And if you don't want key violations while adding data, use merge instead of insert (assuming your SQL Server version is 2008 or later).

How to remove auto increment from table in sql server 2012

I have created a table in SQL Server 2012 with primary key as auto increment. But how can I remove that auto increment property from the table using a SQL query?
If you need to keep the data in that column then create a new column on the table which is of the same type (but a different name), copy the data from the column you want to get rid of to the new one, drop the old column and rename the new. Complete example:
CREATE TABLE test(col1 INT IDENTITY (1,1) NOT NULL, col2 VARCHAR(10) NULL);
ALTER TABLE test ADD col3 INT NULL;
UPDATE test SET col3 = col1;
ALTER TABLE test DROP COLUMN col1;
EXEC sp_rename 'dbo.test.col3', 'col1', 'COLUMN';
The easiest way would be:
Open SQL Server Management Studio.
Locate Server > DataBase > Table.
Right Click on the Table > Select Design.
In the design window, Highlight the column you want to modify.
In the Column Properties Window browse to Identity Specification > Is Identity And set to No.
Go to the toolbar menu > Table Designer > Select Generate Change Script...
Walla, you got the requested script.
I Like using this method for getting scripts, since it allows me to generate scripts I'm not sure how to compose from scratch and thus learning and improving my skills...
If it's a primary key column, then you have to drop the PK first. If there's any tables referencing it, then you'll have to drop these FKs to be able to drop the PK. After that, add another column of the same type, update it with values from identity column, drop the identity column, rename the new column to whatever the name of identity column was (with sp_rename procedure), recreate the PK, recreate the FKs, check if everything went right.
I'd be very careful doing it on a production database. Ensure that noone can access the data while you're doing this.
I searched a lot to find a simple solution to remove the auto increment because i should do a lot of work if i drop the column and the primary key which was a foreign key on another table where I should remove the data that are using my foreign ... finally I ended up with a very simple solution that made my life easy:
SET IDENTITY_INSERT <table_name> ON ;
SET IDENTITY_INSERT [TABLE] OFF .. this allows to remove the auto increment to off state.., so that we have to enter the value in thatcolumn

H2 Database - Reorder columns using SQL

I have a H2 database with 16 million entries and no primary key. I successfully added an auto-incrementing primary key using the following statements:
ALTER TABLE
PUBLIC.ADDRESSES ADD ID BIGINT AUTO_INCREMENT;
ALTER TABLE
PUBLIC.ADDRESSES ADD PRIMARY KEY (ID)
Now the problem is, that the column order is STREET, HOUSENUMBER, ..., ID, but I would like ID to be the first column of the table. It looks like there is a corresponding ALTER TABLE statement MySQL (see here), but I'm unable to adapt it to H2.
Long story short: How can I change the column order to ID, STREET, HOUSENUMBER ...? Is there a solution similar to:
ALTER TABLE "ADDRESSES" MODIFY COLUMN "ID" BEFORE "STREET";
Any help is kindly appreciated.
H2 does not currently support re-ordering columns. You would need to run multiple statements:
First, rename the column, then add a new column with the right name at the right position (alter table add supports positioning), and finally drop the old column.
Or, probably more elegant, use rename table and then create table ... as select.

SQL: Create new column with default, unique value

I have added a new column, called Ordinal, to a table called Activity. The problem is that I gave it a UNIQUE constraint, set it to allow NULL (though this I won't want in the end.. I just needed to set it to that to get a little farther with the script), and did not give it a default value. I'm now running a RedGate SQL Compare script that was generated by comparing this table to a version of the Activity table that does not have the column. But I'm getting the following error:
The CREATE UNIQUE INDEX statement terminated because a duplicate key was found for the object name 'iwt.Activity' and the index name 'IX_Activity'. The duplicate key value is (1).
So based on my research, it's trying to create a unique key constraint on the Ordinal column, but NULL is not unique. So my next step was to give it a unique value of 1 just to let the script pass. But 1 isn't going to be unique either. So, finally, my question:
Preferably in SQL Server Management Studio, how do I set a column as having a unique default value? Isn't that what I would need to create this constraint?
Thanks.
try this:
NULL will be the first constraint when you create the column.
UNIQUE will be as add constraint, you should add the second constraint.
they can run on this order with no problem (tested):
--first constraint
alter table Table_Name
add Column_Name int null
--second constraint
alter table Table_Name
add constraint Constraint_Name unique (Column_Name)
In my example :
PaymentGatewayHash is column
Cart is a table
--first query
alter table Cart
add PaymentGatewayHash NVARCHAR(20) null
--second query
CREATE UNIQUE INDEX PaymentGatewayHashUnique
ON Cart (PaymentGatewayHash)
WHERE PaymentGatewayHash IS NOT NULL
I just tested that :D

Best way to add a new column with an initial (but not default) value?

I need to add a new column to a MS SQL 2005 database with an initial value. However, I do NOT want to automatically create a default constraint on this column. At the point in time that I add the column the default/initial value is correct, but this can change over time. So, future access to the table MUST specify a value instead of accepting a default.
The best I could come up with is:
ALTER TABLE tbl ADD col INTEGER NULL
UPDATE tbl SET col = 1
ALTER TABLE tbl ALTER COLUMN col INTEGER NOT NULL
This seems a bit inefficient for largish tables (100,000 to 1,000,000 records).
I have experimented with adding the column with a default and then deleting the default constraint. However, I don't know what the name of the default constraint is and would rather not access sysobjects and put in database specific knowledge.
Please, there must be a better way.
To add the column with a default and then delete the default, you can name the default:
ALTER TABLE tbl ADD col INTEGER NOT NULL CONSTRAINT tbl_temp_default DEFAULT 1
ALTER TABLE tbl drop constraint tbl_temp_default
This filled in the value 1, but leaves the table without a default. Using SQL Server 2008, I ran this and your code, of alter update alter and did not see any noticeable difference on a table of 100,000 small rows. SSMS would not show me the query plans for the alter table statements, so I was not able to compare the resources used between the two methods.
I'd ALTER TABLE tbl ADD col INTEGER CONSTRAINT tempname DEFAULT 1 first,, and drop the explicitly named constraint after (presumably within a transaction).
Another, maybe more native, way would be:
ALTER TABLE tbl ADD COLUMN col INTEGER NOT NULL DEFAULT 1;
ALTER TABLE tbl ALTER COLUMN col DROP DEFAULT;
I'm not sure how long this function exists, but the PostgreSQL documentation goes back to version 7.1 and for 7.1 it is already described.
You can do it in an insert trigger
If you add a default constraint when creating the table, you won't know what it is called. However, if you add a constraint with ALTER TABLE, you must name the constraint. In this case, you would be able to ALTER TABLE DROP CONSTRAINT (This applies to T-SQL, not sure about other databases.)
However, this would require you to CREATE TABLE with NULL column, ALTER TABLE to add the constraint, make the column NOT NULL, and finally DROP CONSTRAINT.
I don't believe an insert trigger would work as someone else mentioned, because your rows are already added.
I think the way you describe may, in fact, be the most efficient and elegant solution.