Unique Constraint On Nullable Column

Jul 16, 2004

I have a producer table with a nullable column that stores SSN's. In some cases producers inherit SSN's from other producers. These records will have a null producer.ssn and a record stored in a child table to track the inheritance.

Anyway, I've found two techniques to enforce uniqueness on a nullable column and wanted to get opinions as to which was better.

First, write a trigger.

Second, create a computed column that has a unique constraint on it. The computed column would use the SSN if not NULL Else use the PK identity value of the record.

EXAMPLE DML:
CREATE TABLE test (
ssn CHAR(9) NULL,
testId INT identity(1,1) NOT NULL,
ComputedConstraint AS
CASE WHEN ssn IS NULL THEN CAST(testId AS CHAR(9))
ELSE ssn
END, UNIQUE (ComputedConstraint))

Any comments would be greatly appreciated.

View 6 Replies


ADVERTISEMENT

T-SQL (SS2K8) :: Cannot Define Primary Key Constraint On Nullable Column But Column Not Null

Sep 30, 2014

We have a database where many tables have a field that has to be lengthened. In some cases this is a primary key or part of a primary key. The table in question is:-

/****** Object: Table [dbo].[DTb_HWSQueueMonthEnd] Script Date: 09/25/2014 14:05:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[DTb_HWSQueueMonthEnd](

[Code] ....

The script I am using is

DECLARE@Column varchar(100)--The name of the column to change
DECLARE@size varchar(5)--The new size of the column
DECLARE @TSQL varchar(255)--Contains the code to be executed
DECLARE @Object varchar(50)--Holds the name of the table
DECLARE @dropc varchar(255)-- Drop constraint script

[Code] ....

When I the the script I get the error message Could not create constraint. See previous errors.

Looking at the strings I build

ALTER TABLE [dbo].[DTb_HWSQueueMonthEnd] DROP CONSTRAINT PK_DTb_HWSQueueMonthEnd
ALTER TABLE [dbo].[DTb_HWSQueueMonthEnd] Alter Column [Patient System Number] varchar(10)
ALTER TABLE [dbo].[DTb_HWSQueueMonthEnd] ADD CONSTRAINT PK_DTb_HWSQueueMonthEnd PRIMARY KEY NONCLUSTERED ([Patient System Number] ASC,[Episode Number] ASC,[CensusDate] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

They all seem fine except the last one which returns the error

Msg 8111, Level 16, State 1, Line 1
Cannot define PRIMARY KEY constraint on nullable column in table 'DTb_HWSQueueMonthEnd'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.

None of the fields I try to create the key on are nullable.

View 2 Replies View Related

Unique Column Constraint

Jun 6, 2008

I like to use the management console to design tables, but have
been unable to figure out how to add a unique column constraint.

I have a primary key defined in col1 and want to make col2, char(10),
unique, but keep col1 as the primary key.

I have tried the Check constraint menu path, but do not know how
to write the expression.

If I go along the Indexes/Key path, I am forced to change the primary
key which I do not want to do.

Can anyone help?

TIA, Joe

View 5 Replies View Related

How To Drop UNIQUE CONSTRAINT On Only One Column

May 5, 2014

I am very new to sql and I have got this doubt.

CREATE TABLE employee
{ EMP-ID VARCHAR UNIQUE,
DESIG VARCHAR UNIQUE,
SALARY INT };

Probably this is worst table ever created :).Now How to drop UNIQUE constraint on only column lets DESIG.

if i write

ALTER TABLE employee
DROP CONSTRAINT myuniqueconstraint;

will drop constraints on both columns which I dont want.

Any query that remove UNIQUE CONSTRAINT only on DESIGN column.

and one more clarification,

ALTER TABLE employee
MODIFY SALARY INT NOT NULL;

ALTER TABLE employee
ALTER COLUMN SALARY INT NOT NULL;

which of the above two is right query to add NOT NULL constraint to the above employee TABLE?

View 1 Replies View Related

Unique Constraint Based On Value In A Column

Nov 23, 2007

I don't immediately find if this is possible but hope someone can give me an answer:
is it possible to make a unique constraint over 2 columns but only when 1 column has a specific value ?

Example: table (tableid, instancetype, instancename, ..)
instancetype can be A or B
if it is A then instancename must be unique
but for B instancename is not unique as these are copies from A

only solution I can think of is to make a trigger on an insert to check what the instancetype is and do a select to see if the name already exists in the table or not..

are there other solutions to make a constraint like this ?

Aeneas.

View 1 Replies View Related

Unique Constraint To A Column From Another Table

Oct 29, 2005

Is it possible to create a unique constraint to a column from anothertable? For example:tb_current:current_names--------------aaabbbtb_new:new_name--------cccNow I want to create a constraint on tb_new.new_name to be unique withrespect to tb_current.current_names. However, tb_new.new_name shouldnot be unique to itself. So I should not be able to insert 'aaa' totb_new.new_name. But I should be able to insert 'ccc' totb_new.new_name.Here's the script to reproduce this example:create table tb_current(current_names varchar(10))create table tb_new(new_name varchar(10))insert tb_current values ('aaa')insert tb_current values ('bbb')insert tb_new values ('ccc')select * from tb_currentselect * from tb_newinsert tb_new values ('aaa') -- this should NOT be allowedinsert tb_new values ('ccc') -- this should be allowed

View 3 Replies View Related

UNIQUE Constraint On VARBINARY Column

Nov 17, 2006

Hi,

I have a table with one of its column VARBINARY(MAX).

I want to make sure that the values in this VARBINARY(MAX) column is unique.
SQL Server doesn;t allow to create Unique Constraint over VARBINARY fields - whats the best workaround for ensuring uniqueness on VARBINARY columns.

Thanks,
Loonysan

View 1 Replies View Related

Unable To Create Unique Constraint On A NULL Column

Apr 5, 2004

Hi all,

I am trying to add a unique index/constraint on a column that allows NULL values. The column does have NULL values and when I try to create a unique constraint, I get the following error.

CREATE UNIQUE INDEX terminated because a duplicate key was found for index ID 9. Most significant primary key is '<NULL>'.

Are'nt you allowed to create a UNIQUE constraint on a NULL column? Books Online says that you are allowed to create a unique constraint on NULL columns, then why am I getting this error.

Any help would be appreciated.
Thanks,
Amir

View 8 Replies View Related

SQL Security :: Enforcing Unique Constraint On A Column Encrypted With Cell Level Encryption?

May 11, 2015

I want to enforce a unique constraint on a column which must be encrypted in MSSQL 2005 using Cell Level Encyption (CLE).

    CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'itsaSECRET!!!3£3£3£!!!'
    CREATE CERTIFICATE ERCERT WITH SUBJECT = 'A cert for use by procs'
    CREATE SYMMETRIC KEY ERKEY
    WITH ALGORITHM = AES_256
    ENCRYPTION BY CERTIFICATE ERCERT

[Code] ....

The output makes it obvious why the constraint has 'not' been enforced.

        Email
       -------
    1 | 0x00703529AF46D24BA863A3534260374E01000000328909B51BA44A49510F24DF31
C46F2E30977626D96617E2BD13D9115EB578852EEBAE326B8F3E2D422230478A29767C
    2 | 0x00703529AF46D24BA863A3534260374E01000000773E06E1B53F2C57F97C54370FECBB45B
C8A154FEA5CEEB9B6BB1133305282328AAFAD65B9BDC595F0006474190F6482
    3 | 0x00703529AF46D24BA863A3534260374E01000000C9EDB1C83B52E60598038D832D34
D75867AB0ABB23F9044B7EBC76832F22C432A867078D10974DC3717D6086D3031BDB

But, how do I work around this?

View 8 Replies View Related

What Is The Difference Between A UNIQUE INDEX And A UNIQUE CONSTRAINT?

Sep 22, 2004

A UNIQUE INDEX must inherently impose a unique constraint and a UNIQUE CONSTRAINT is most likely implemented via a UNIQUE INDEX. So what is the difference? When you create in Enterprise Manager you must select one or the other.

View 8 Replies View Related

Unique Constraint Vs Unique Index In MS SQL 2000

Jul 20, 2005

HelloWhat should I use for better perfomance sinceunique constraint always use index ?ThanksKamil

View 5 Replies View Related

Unique Constraint And Unique Index, What's The Difference?

Jun 24, 2006

What's the difference in the effect of the followings:
CREATE UNIQUE NONCLUSTERED INDEX
and
ALTER TABLE dbo.titles ADD CONSTRAINT
titleind UNIQUE NONCLUSTERED

I found there're two settings in Indexs/Keys dialog box of the management studio, Is Unique, and Type. The DDL statements above are generated by setting Is Unique to yes plus Type to Index, and just Type to Unique Key, respectively. What's the difference between them?

View 1 Replies View Related

Unique Constraint Error When There Is No Constraint

May 13, 2008

We are using SQL CE 3.5 on tablet PCs, that synchs with our host SQL 2005 Server using Microsoft Synchronization Services. On the tablets, when inserting a record, we get the following error:
A duplicate value cannot be inserted into a unique index. [ Table name = refRegTitle,Constraint name = PK_refRegTitle
But the only PK on this table is RegTitleID.

The table structure is:
[RegTitleID] [int] IDENTITY(1,1) NOT NULL,
[RegTitleNumber] [int] NOT NULL,
[RegTitleDescription] [varchar](200) NOT NULL,
[FacilityTypeID] [int] NOT NULL,
[Active] [bit] NOT NULL,

The problem occurs when a Title Number is inserted and a record with that number already exists. There is no unique constraint on Title Number.
Has anyone else experienced this?

View 3 Replies View Related

Unique Index Vs Unique Constraint

Mar 7, 2001

Hi everyone,
I need urgent help to resolve this issue...
As far as the performance goes which one is better..
Unique Index(col1, col2) OR Unique constraint(col1, col2) ?
Unique constraint automatically adds a unique index
and unique index takes care of uniqueness then whats the use of unique constraint ?

Which one do one use ?

thanks
sonali

View 4 Replies View Related

Unique Constraint Vs Unique Index

Jan 20, 2006

BOL says a unique constraint is preferred over a unique index. It also states that a unique constraint creates a unique index. What then is the difference between the two, and why is a constraint preferred over the index?

View 2 Replies View Related

Set Column Nullable

Dec 12, 2000

Is there a way to set a column nullable in a script if all I have is the column name, something like:

exec('ALTER TABLE xyz ALTER COLUMN ' + @col_name + ' NULL')

The problem is that ALTER TABLE requires the type, so you have to say something like:

exec('ALTER TABLE xyz ALTER COLUMN ' + @col_name + ' decimal(12,4) NULL')

But the data type is not given to the script, so it is stuck.

I realize that syscolumns provides some relevant information, but it is not clear how to convert its information to a string like "decimal(12,4)". It seems, for example, that a decimal type has syscolumns.xtype = 106; however I can find no documentation on this, nor am I assured I can get all the right codes by trial and error. Does anyone know of a clear means of getting this information?

View 1 Replies View Related

One Column Is Nullable On The Composite Key

Jul 20, 2005

Hi All!I would like to have a composite PK on 3 columns, one of them is nullCREATE TABLE TableA (ColA int NOT NULL ,ColB int NOT NULL ,ColC char (3) NULL ,......)GOALTER TABLE TableA ADDCONSTRAINT TableA_PK PRIMARY KEY CLUSTERED(ColA,ColB,ColC)GOSQL Server does not allow having a composite PK with one nullable column:What is wrong to have values?1,100,NULL1,200,ABC1,200,ABD.....Code in C applies to Values in B and for some values in B the code does not exist.I can work out and define a special Code:NEV(not existing value), but in general I do not understand this restriction.Thanks

View 3 Replies View Related

How Do I Make A Column Not Nullable

Apr 26, 2006

This is what I would like to do...

1. Alter Table Status
Add ConsiderOpenFlag int null

2. UPDATE values...

3. Alter Table Status
Alter ConsiderOpenFlag int not null

Steps 1 and 2 are easy. What I cannot figure out is step three.

I don't want to have a default on that column, though I wouldn't mind adding it and then dropping it later if it would help.

Jonathan



View 1 Replies View Related

Comparing Nullable Column With Int

Sep 20, 2007



Hi,

I have a table name bla.
PKEY id, int, NOT NULL
group, int
name, string, NOT NULL

how do I compare them with int?

for example the following data.
1, NULL, 'freelance'
2, 1, 'group1'
3, 2, 'group2'


select * from bla where group<>1 <-- this fails?

What is the proper SQL Statement for this?


Regards,
Max

View 1 Replies View Related

Creating Primary Key On Nullable Column

Feb 29, 2008

Hello,

I am trying to recreate a primary key that I dropped in a table....

I'm using a statement like

ALTER TABLE temp WITH NOCHECK add CONSTRAINT PK__tempkey PRIMARY KEY CLUSTERED

(

num,
store
)


But apparently the "store" column was created without a "not null" and it let it create the PK during the table creation but now it won't let me add the PK with that nullable column..

Does anyone know how to get it to use that column to create a primary key after the initial table creation?

Here is the error i get

Cannot define PRIMARY KEY constraint on nullable column in table


Thanks a lot

View 5 Replies View Related

Add UNIQUE Constraint

May 13, 2006

Hi,I want to add unique contraint to EXISTING column in EXISTING table.I have ms sql 2005.How to do that?

View 7 Replies View Related

Unique Constraint

Nov 19, 2001

Does anyone have any Idea on how I could enforce a unique constrait across multiple tables?

View 1 Replies View Related

Unique Constraint

May 19, 2004

What is the simplest way to add a unique constraint on a field of type varchar(7) that can allow any number of <NULL>'s?

I only want to ensure that when this field is updated, it is updated with a value that has not been used.


IF EXISTS (SELECT Project FROM tbProjects WHERE Project = @cProject)
RAISERROR('Project number already used!',16,1)
ELSE
UPDATE tbProjects SET Project = @cProject WHERE ProjectID = @iProjectID
GO


Also, I cannot allow the user to chante the project field value once it is set.


Any suggestions?

Mike B

View 14 Replies View Related

Unique Constraint

Apr 4, 2008

Anybody knows how to make two columns in a table unique?

View 1 Replies View Related

UNIQUE Constraint

Aug 16, 2006

i'm just creating a table, no data as yet.

i have a varchar(15) fld with Nulls NOT allowed

i want to create a constraint that this field named ipkey be UNIQUE.

I'm having trouble with the syntax for the constraint expression.

i've typed in the SQL Server Managment Studio Express Expression field:
UNIQUE(ipkey)
and
@unq_ipkey UNIQUE(ipkey)

SQL Server Managment Studio Express complains:
"Error validating constrating, do you want to edit expression"

So - what am i doing wrong?
And thanks for taking the time to help.

View 2 Replies View Related

Unique Constraint

Dec 3, 2007

Hi,

I have a table with two column, c1 and c2. c1 is set as primary key. I want c2 to be set with unique constraint.

I choose this talbe in object explorer, right click and select modify. Then I choose "index/key" from "table designer" menu.

The problem is that in the "index/key" dialog, the "Columns" item (under General) is always c1. if I click the "..." button to popup "index column", I could only choose either "c1" or <None> under "column name" dropdownlist.

How could I choose c2 and set unique constraint on it?

Thx
Tao

View 3 Replies View Related

Constraint Unique Row

Apr 11, 2008



Hi,

I need to define a constraint , to prevent some fields of a table to be duplicated, How can i define this constraint ?

View 3 Replies View Related

A Unique Unique Constraint

May 1, 2008

Here is the table I created:

create table Test (
[recId] [int] identity(1, 1) not null,
[code] [varchar](50) not null,
[prime] [bit] not null constraint [DF_Test_prime] default (cast(0 as bit)),
constraint [PK_Test] primary key clustered
(
[recId]
) with fillfactor = 90 on [primary]
) on [primary]
go

insert into Test (code, prime) values ('AVA', cast(1 as bit))
insert into Test (code, prime) values ('BUS', cast(1 as bit))
insert into Test (code, prime) values ('BUS', cast(0 as bit))
insert into Test (code, prime) values ('BUS', cast(0 as bit))
insert into Test (code, prime) values ('CAR', cast(1 as bit))
insert into Test (code, prime) values ('CAR', cast(0 as bit))
insert into Test (code, prime) values ('RLW', cast(1 as bit))
insert into Test (code, prime) values ('RLW', cast(0 as bit))
insert into Test (code, prime) values ('RLW', cast(0 as bit))

select *
from Test

I need to create a constraint on this table that will not allow me to have two rows that are prime for the same code. So the following insert statement should fail:

-- This should fail
insert into Test (code, prime) values ('RLW', cast(1 as bit))


Thanks for you help!

Regards,
Anand

View 11 Replies View Related

Sql Exception Unique Key Constraint

Oct 25, 2007

 
Hi All,
I am trying to catch a specfic unique key constraint in a table.
i my table i have two fields USERID And EMAILID and i set both to unique.
now on registration form i am checking that USERID or EMAIID is already present or not.
by taking ex.number =2627 i am not able to find which unique key constraint is getting violated.
is there any other way to find it.
thanks in advance.

View 1 Replies View Related

Can&#39;t Create Unique Constraint

Nov 3, 2000

I am attempting to create a unique constraint on an nvarchar field named theology (it is not the primary key field)
that allows nulls. The table contains multiple rows with the value of null for
field theology. The documentation says one can create a unique constraint on a
field with all unique value except for null. Here is the error message:

'testtable1' table
- Unable to create index 'IX_testtable1'.
ODBC error: [Microsoft][ODBC SQL Server Driver][SQL Server]CREATE UNIQUE INDEX
terminated because a duplicate key was found. Most significant primary key
is ''.
[Microsoft][ODBC SQL Server Driver][SQL Server]Could not create constraint. See
previous errors.

Any ideas? I am creating a unique constraint and not a unique index. Is there
some other database option to set to allow this?

.

View 2 Replies View Related

Unique Constraint Question

Sep 12, 2003

when we use Unique constraint over a column it allows null values.
but then null values are duplicating, how is that?

thanks

View 3 Replies View Related

Unique Constraint With Conditioning?

May 4, 2005

Hi All:

Is there a way to create a unique constraint with 4 fields combined, such as colA, colB, colC, and colD.

but colD is for all the values but value = 3.

If this does not work out, trigger probably is the last way I would like to approach. and it is slower than constraint with many inserts.

thanks
David

View 2 Replies View Related

Add Unique Constraint On 3 Fields?

Jul 21, 2015

I want to add a unique constraint on 3 fields, to only allow the value in the field ONE time. The value will NEVER be the same for anything else. This is the table structure

Code:
Create Table Employees
(
P_Id int NOT NULL,
InstructorName varchar(255) NOT NULL,
CourseName varchar(100) NOT NULL,
DataTableName varchar(100) NOT NULL
)

I want to create a unique constraint across the fields Instructorname, CourseName, DataTableName as their is ONLY 1 instructor per course per table so those 3 fields will ALWAYS hold unique values. I think the constraint syntax would go like so, but want to check before I go butchering some sql syntax.

constraint syntax:

Code:
Alter Table Employees
Contstraint uniqueEmployee Unique (InstructorName ,CourseName ,DataTableName )

View 1 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved