Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
aamir1
Starting Member
2 Posts |
Posted - 2007-03-02 : 02:53:09
|
| how can i apply unique cosntraint in an existing table's columni want to do it like this as belowsql server enterprise manager ==> DB==>table (R.click)==>design table |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2007-03-02 : 03:16:21
|
I took the liberty to quote Books Online regarding ALTER TABLE statementquote: E. Adding an unverified CHECK constraint to an existing columnThe following example adds a constraint to an existing column in the table. The column has a value that violates the constraint. Therefore, WITH NOCHECK is used to prevent the constraint from being validated against existing rows, and to allow for the constraint to be added. Copy Code CREATE TABLE doc_exd ( column_a INT) ;GOINSERT INTO doc_exd VALUES (-1) ;GOALTER TABLE doc_exd WITH NOCHECK ADD CONSTRAINT exd_check CHECK (column_a > 1) ;GOEXEC sp_help doc_exd ;GODROP TABLE doc_exd ;GO F. Adding a DEFAULT constraint to an existing columnThe following example creates a table with two columns and inserts a value into the first column, and the other column remains NULL. A DEFAULT constraint is then added to the second column. To verify that the default is applied, another value is inserted into the first column, and the table is queried. Copy Code CREATE TABLE doc_exz ( column_a INT, column_b INT) ;GOINSERT INTO doc_exz (column_a)VALUES ( 7 ) ;GOALTER TABLE doc_exzADD CONSTRAINT col_b_defDEFAULT 50 FOR column_b ;GOINSERT INTO doc_exz (column_a)VALUES ( 10 ) ;GOSELECT * FROM doc_exz ;GODROP TABLE doc_exz ;GO G. Adding several columns with constraintsThe following example adds several columns with constraints defined with the new column. The first new column has an IDENTITY property. Each row in the table has new incremental values in the identity column. Copy Code CREATE TABLE doc_exe ( column_a INT CONSTRAINT column_a_un UNIQUE) ;GOALTER TABLE doc_exe ADD -- Add a PRIMARY KEY identity column.column_b INT IDENTITYCONSTRAINT column_b_pk PRIMARY KEY, -- Add a column that references another column in the same table.column_c INT NULL CONSTRAINT column_c_fk REFERENCES doc_exe(column_a),-- Add a column with a constraint to enforce that -- nonnull data is in a valid telephone number format.column_d VARCHAR(16) NULL CONSTRAINT column_d_chkCHECK (column_d LIKE '[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]' ORcolumn_d LIKE'([0-9][0-9][0-9]) [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]'),-- Add a nonnull column with a default.column_e DECIMAL(3,3)CONSTRAINT column_e_defaultDEFAULT .081 ;GOEXEC sp_help doc_exe ;GODROP TABLE doc_exe ;GO
Peter LarssonHelsingborg, Sweden |
 |
|
|
|
|
|
|
|