Constraint/identity Which Allows Duplicate Null Fields

Jan 4, 2007

hi,

I've done Googling and forum hunting but haven't had success finding a simple answer... My table schema is such that it requires the (int) LinkedItemID field to be nullable but still those fields which are set must not be duplicates. I see constraint is out of question and also identity doesn't seem to fit since I'm not using autofill for this particular field. Is there some other way doing this on Sql Server 2005?

 

Thank you.

View 7 Replies


ADVERTISEMENT

Unique Constraint Does Not Permit Duplicate NULL Values

Oct 2, 2000

After adding a Unique constraint to a database I cannot add more than one record with a null value for the constrained field. I've tried both adding the constraint to an empty table as well as a table with multiple null values already in the subject field; both efforts have failed.

According to BOL SQL-7 allows Unique Constraints on fields with Null values. Am I missing a step? I do need to allow nulls in the field yet ensure that when there is a non-null value it is unique.

The SQL statement I've used is: ALTER TABLE tbl_MasterUIC ADD CONSTRAINT uniquesamplenbr UNIQUE NONCLUSTERED (samplenbr)

Thanks for any and all suggestions

View 2 Replies View Related

Setting Duplicate Fields To NULL

Mar 19, 2008



I have a result set stored in a temporary table variable. The fields need to have heirarchy when they finaly get displayed to the user. I need to replace the repeating fields per group with NULL and leave out only one set of unique records per group.

I want to do something like this- make the fields in red NULL while leaving out the ones in green.

{ Col.Group I } { Col. Group II }

Col1 Col2 Col3 Col4 Col5
------- ------- ------- ------- -------
ValA ValA2 ValA3 ValA40 ValA50 {
ValA ValA2 ValA3 ValA40 ValA50 Row. Group A
ValA ValA2 ValA3 ValA41 ValA51 }

ValB ValB2 ValB3 ValB40 ValA50 { Row. Group B
ValB ValB2 ValB3 ValB41 ValA51 }



I was able to achieve this by using @@ROWCOUNT with in a while loop by performing one UPDATE at a time (SET ROWCOUNT = 1). But i have to run Count(*) each time I loop through the update query to figure out the remaining number of rows I have per group as I need to leave out one untouched. But the Count function is taking too much time and I'm having performace issues.

Any idea how I might be able to do this in my stored proc. efficiently?

Thanks,

Samtadsh

View 8 Replies View Related

Named Constraint Is Not Supported For This Type Of Constraint (not Null)

May 13, 2008

Hi, all.

I am trying to create table with following SQL script:





Code Snippet

create table Projects(
ID smallint identity (0, 1) constraint PK_Projects primary key,
Name nvarchar (255) constraint NN_Prj_Name not null,
Creator nvarchar (255),
CreateDate datetime
);

When I execute this script I get following error message:

Error source: SQL Server Compact ADO.NET Data Provider
Error message: Named Constraint is not supported for this type of constraint. [ Constraint Name = NN_Prj_Name ]

I looked in the SQL Server Books Online and saw following:

CREATE TABLE (SQL Server Compact)
...
< column_constraint > ::= [ CONSTRAINT constraint_name ] { [ NULL | NOT NULL ] | [ PRIMARY KEY | UNIQUE ] | REFERENCES ref_table [ ( ref_column ) ] [ ON DELETE { CASCADE | NO ACTION } ] [ ON UPDATE { CASCADE | NO ACTION } ]

As I understand according to documentation named constraints should be supported, however error message says opposite. I can rephrase SQL script by removing named constraint.





Code Snippet

create table Projects(
ID smallint identity (0, 1) constraint PK_Projects primary key,
Name nvarchar (255) not null,
Creator nvarchar (255),
CreateDate datetime
);
This script executes correctly, however I want named constraints and this does not satisfy me.

View 1 Replies View Related

CHECK Constraint To Prevent A Conditional Duplicate

Jul 23, 2005

Hi,I need to enforce that a table does not have "duplicates" for aspecific status type in the table.If the column "STATUS" = 2, then there can not be more than one rowwith a specific "ID" column.I can not use a unique key constraint because duplicate values for thiscombo of columns is valid for the status = 1.Just when the status = 2, there can not be any other rows with the sameID and status = 2.Any ideas?-Paul

View 3 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

Check Constraint For 2 Fields

Apr 11, 2007

Hi , I have a table that holds CityName and TownName.This table is usually updated and I dont want the same CityName and TownName to be inserted Again.
I have used Primary Key that holds thoose two fields but Primary Key is an index and I know that using check constraint works by spending less performance then indexes .

So , How can I use a check Constraint for two fields ?

Thanks ...

View 1 Replies View Related

SP Causes The Error Violation Of UNIQUE KEY Constraint Cannot Insert Duplicate Key

Dec 23, 2007

The following SP causes the error "Violation of UNIQUE KEY constraint 'AlumniID'. Cannot insert duplicate key in object [table name].
The statement has been terminated." AlumniID is the table's PK and is set to autoincrement. I'd appreciate any help or suggestions.

1 ALTER PROCEDURE dbo.sp_CreateUser
2
3 @UserID uniqueidentifier,
4 @UserName nvarchar(128),
5 @Email nvarchar(50),
6 @FirstName nvarchar(25),
7 @LastName nvarchar(50),
8 @Teacher nvarchar(25),
9 @GradYr int
10
11 AS
12 SET NOCOUNT ON;
13 --DECLARE @UserID uniqueidentifier
14 --SELECT @UserID = NULL
15 --SELECT @UserID = UserID FROM dbo.aspnet_Users WHERE LOWER(@UserName) = LoweredUserName-- AND @ApplicationId = ApplicationId
16 INSERT INTO [table]
17 (UserID,UserName,Email,FirstName,LastName,Teacher,GradYr)
18 VALUES (@UserID,@UserName,@Email,@FirstName,@LastName,@Teacher,@GradYr 

View 2 Replies View Related

SP Causes The Error Violation Of UNIQUE KEY Constraint Cannot Insert Duplicate Key

Mar 14, 2008



I have a table with 0 records. When I try to insert records using a SP, it gives the following error.
Violation of UNIQUE KEY Constraint 'constraint name'. Cannot insert duplicate key in object 'Objectname'.
How do I resolve this.
Thanks.

View 1 Replies View Related

ALTER TABLE APLLYING IDENTITY CONSTRAINT

Apr 9, 2008

Pls help me

i want to alter table and add identinty constraint on one column

create table play8(id int)
" alter table play8
alter column id int identity(1,1) " GIVES ERROR or it is posibble


Yaman

View 1 Replies View Related

Violation Of PRIMARY KEY Constraint 'PK_tblType'. Cannot Insert Duplicate Key In Object 'dbo.tblType'.

Oct 19, 2007

the point here that i have a small table with two fileds,
ID (guid) as primerykey
RAF(char)
and the table is empty when i add a new row i recieve this exception,
Violation of PRIMARY KEY constraint 'PK_tblType'. Cannot insert duplicate key in object 'dbo.tblType'.
i found no way to solve the problem.
thanks in advans
 

View 7 Replies View Related

Unique Constraint And Null?

Feb 27, 2008



Can I create a unique constraint on a column that can contain null values?
I need the control of the non null values (must be unique)...null is Ok if there's more than one.
I tried creating a unique constraint but i'm getting the error (duplicate keys <null>)

View 20 Replies View Related

Getting Duplicate Identity Values In SQL 6.5

Aug 26, 1998

We are experiencing a problem at more than one site - it has only
just started happening.

We are actually getting duplicate Identity column values in various
tables and the values seem random - its not like the counter just gets
wound back.

We have used dbcc checkident and also bcp out and in the data, which
of course corrected the tables but only temporarily. Our application
is not doing any select into`s - just plain old inserts which for some
reason are allowing dups to be inserted into the tables.

problem sites are either sp3 or sp4.

There are thousands of sites (including most of ours) where there are
no problems like this with this particular app.

Any help from anyone would be most appreciated.

View 1 Replies View Related

Duplicate Records - Two Fields

Feb 13, 2014

I have a table that contains some duplicate records. The entire record is not duplicated, but there are two fields which if both are duplicated, result in what I call a duplicate record. I can see that I have these duplicates by doing the following:

SELECT DISTINCT ReferenceNumber, ShipToCompanyID
FROM tabMedia
WHERE (MediaTypeID = '1') AND (FinishDate > '2011-01-01')
GROUP BY ReferenceNumber, ShipToCompanyID
HAVING (COUNT(ReferenceNumber) > 1) AND (COUNT(ShipToCompanyID) > 1)
ORDER BY ReferenceNumber

but of course, this only returns two fields. I need the entire record returned where the duplicate exists...

View 2 Replies View Related

Alter Table Add Constraint Null Value

Dec 1, 2007

I have a stored procedure that adds constraints from a variable:
ALTER procedure [dbo].[addMyConst](@txtAuto_ourlim money OUTPUT,@txtGen_ourlim money OUTPUT)ASEXECUTE('ALTER TABLE [dbo].[tbl1] ADD CONSTRAINT DF_auto_ourlim DEFAULT ' + @txtAuto_ourlim + ' FOR Auto_ourlim')EXECUTE('ALTER TABLE [dbo].[tbl1] ADD CONSTRAINT DF_Gen_ourlim DEFAULT ' + @txtGen_ourlim + ' FOR Gen_ourlim')
This works fine unless one of the variables is null or empty. Then I get the  error: "Incorrect syntax near the keyword 'FOR'
Evidendly SQL Server Express sees "....DEFAULT + + FOR..." but I don't know.
I've fiddled with this a long time and haven't a clue how to fix it. Any help would be appreciated. Thanks, Steve

View 2 Replies View Related

Temporarily Dropping Not-null Constraint

Nov 15, 2007

I am doing a data conversion in which I drop constraints before inserting data and then reapply at the end. I would like to also drop the not null constraints for certain columns, transfer the nulls and then fill them in later before reapplying the constraints. Is there a relatively simple way to drop and reapply the not null constraints?

View 4 Replies View Related

How To Reset The Identity Counter On A Table Referenced By A FOREIGN KEY Constraint?

Apr 4, 2006

I know that TRUNCATE TABLE can be used to reset the identity counter, but it can't be used on a table referenced by a foreign key. Anybody knows how to do that? Thanks.

View 4 Replies View Related

Q:Duplicate A Record Except One Or Two Specific Fields Using SQL

Oct 30, 2000

Using Transact-SQL how can I copy all fields except one from one record to another? The field in question being the identity field. Since, this field cannot be duplicated a simple INSERT statement fails. How can I specify an exclusion list of fields?

-Sumit

View 1 Replies View Related

Duplicate Data For Unique Fields With Different Name?

Oct 25, 2013

I'm designing an app for stock keeping. In my DB, I have a field called "ItemSerialNo" and I made it unique(but not the table's primary key). On my front end, I have a text box for Item Serial No and a combo box loaded with the item brands and also a save button. I know that if I try to save a serial no already existing in my DB, the app won't allow me because of the unique property of the field named "ItemSerialNo". But I want to be able to save a serial no already existing in my DB but with a different brand name.

For example, I want to be able to save information like:

1. ITEM SERIAL NO = 12345
BRAND NAME = AA
2. ITEM SERIAL NO = 12345
BRAND NAME = BB.

View 2 Replies View Related

Check Constraint Does Not Work (compare With Null)

Mar 20, 2006

Hi!I have a table with a check constraint. But unfortunately it does notwork like I wanted.CREATE TABLE MAP([R_ID] [T_D_ID] NOT NULL,[R_ID1] [T_D_ID] NULL,CONSTRAINT CHECK_ID1 CHECK (R_ID1 = R_ID OR R_ID1 = NULL),CONSTRAINT [PK_MAP] PRIMARY KEY ([R_ID]))R_ID1 should always have the value of R_ID or NullThe following statements should cause errors:insert into map (R_ID, R_ID1)values(1,2);update map set R_ID1=3 where R_ID=1;But there occur no errors. Does anyone have an idea? It is an SQL Server2000.TIASusanne

View 6 Replies View Related

'Cannot Insert Duplicate Key' Error With Identity Column As PK

Feb 18, 2008



I guess there is first for everything...I had never seen error like this before

Violation of PRIMARY KEY constraint 'PK_table1'. Cannot insert duplicate key in object 'table1'. The statement has been terminated.

In this case Primary Key is Identity column. I do not include Idenity column in Insert statement.



Incidently SQL server machines had cluster failure couple of days before. I am not sure whether it has anything to do with it.


I see this error randomly.

How should I debug it

View 1 Replies View Related

Find Duplicate Records Based On Certain Fields

Jul 28, 2014

How can I pull out duplicate records based on certain fields?

Table called Bank

I want to pull out records that have duplicate inv_no, cus_no, amount,ordernum

Not all the fields are the same in each record. But I want the records that have these fields that are the same.

View 1 Replies View Related

Identity Fields - Why Use Them

May 29, 2007

I am building a database for a new project. I am not a DBA or a database designer so please bear with me on this question.
My boss believes that the only time to use an identity column is when we cannot determine a unique primary key.  On tables where we can determine a unique primary key identify fields are a waste of reasources. For instance, one of the tables that I need to create is a customer table. Since all of our customers have unique customer numbers my boss believes that in this case an identity column is useless.   I don't have enough experience to determine if he is correct or not.  
Can someone please explain the pro's and con's of using identity fields to me. 
Thanks

View 6 Replies View Related

Identity Fields

Mar 16, 2004

how do I start an auto increment field at a certain number? other than 1

View 2 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

Identity Column On Table And Ignore Duplicate On Index

Mar 27, 2007

Hello,

I have a table with an Identity Column set up. I also have an index on the table that is set to Ignore Duplicate. Identity starts at 1 and is incremented by 1.



So first 5 rows inserted get identity

1

2

3

4

5



If I insert rows that get ignored because of the index with Ignore Duplicate, it is ignored correctly. But, the next row to get inserted will have an identity value of 7.



So, even though the insert was ignored because of the index with Ignore Duplicate, the Identity column was incremented behind the scenes.



Is there any way to avoid this?



Thanks,

John

View 3 Replies View Related

Advanced Identity Fields

Apr 19, 2007

Hi!
a) PROBLEM 1:
I have set up my main database like this (of course I'm showing an abbreviation):
company - int (identity)name - nchar
I have several companies stored in the previous table. Now I have another table with messages:
company - int (related with the company of the previous table)messageID - int (identity)contents - nchar
company and messageID are the main key of this table. I want to set the messageID column to change automatically. Since I declared it as identity it is working fine, but I was looking to start it on 0 on every new company:
Company messageID0              00              10              21              0 <- Here the company changed, so the messageID resets1              11              21              32              0 <- Again2              1
Any suggestions?
b) PROBLEM 2:I have my database stored locally on my computer. When I finished working with the database it has a lot of data for testing. I want to upload the database to my hosting provider or to my customer's. But the identity columns keep incrementing since the last value of my tests, so it's kind of annoying to see values as: 1250, 223, etc. when I expect to see 0,1, 2 and so on. Also, for receipts this is a very important issue.
How can I reset the identity fields?
Thank you very much for your attention and help.
CT

View 3 Replies View Related

Some Problem With Identity Fields

Aug 8, 2007

 HiI've a tabel with two columns as identity fields (one as primary key), but I read in SQL 2000 documentation that it is permitted only one column as identity, it's true?The second field has to be autoincrement so I supposed to use identity field for it...Now the true problem, supposing that I can use two identity fields...I'd like to reset the second identity when the year change... In other words, I've to manage some spedition which are identified with XXX/year, where XXX is a number.Coming from Oracle, I supposed to use a trigger on insert which reset the sequence when the year changa, but in MS??Tnx... 

View 2 Replies View Related

Identity/autonumber Fields

Sep 13, 1999

I am experiencing a problem with the identitynumber field in SQL vs the autonumber field in MS Access 97. When I open the Member Contact form(Access), it generates the autonumber on the form, which is then visible on the form itself. That form has several pulldown/pop-up boxes which are used to select criteria. One of the form buttons, the Add Comments button, once pushed, it brings up a Comments form. This Comments form references the autonumber that was generated on the Member Contact form in order to open itslef. The information is then entered into the Comments form and the form is then saved. All the selected information is saved to that record upon the saving of that form.

Now, my problem has to do with getting the identity number(SQL) to generate on the Member Contact form and also allowing the Comment form to open by referencing that generated identitynumber just like Access does without having to save the record first then coming back and adding a comment later.

Do anyone know if it is possible? If so, does anyone have any suggestions on how to generate a identitynumber before saving the entire record?

View 2 Replies View Related

Adding Identity Fields

Nov 2, 1998

I have a table that I need to add an identity field to. I created a field in the table as an INT and added values to all of the existing records. When I try to change it to an IDENTITY field I continually get an error saying 'Invalid cursor state' . The help function tells me that this is caused by not having enough space in the transaction log but I don't understand this b/c the trans log is configured to expand as needed. Anyone know how I can do this?

Thanks,
Tony

View 2 Replies View Related

Stuck Between Cannot Insert The Value NULL Into Column 'ID' And Violation Of PRIMARY KEY Constraint

Jan 20, 2004

Cannot find an answer to this in previous posting, though there are similar topics.

My primary key "ID" requires a value (is not nullable), and not explictly providing it with one when I update a new record gives the following error:

Cannot insert the value NULL into column 'ID', table 'AdClub.mediaq.News'; column does not allow nulls. INSERT fails.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'ID', table 'AdClub.mediaq.News'; column does not allow nulls. INSERT fails.

However, trying to stuff that field with a recordCount+1 value (or any value), I get this error:

Violation of PRIMARY KEY constraint 'Primary Key'. Cannot insert duplicate key in object 'News'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Violation of PRIMARY KEY constraint 'Primary Key'. Cannot insert duplicate key in object 'News'.

Cannot figure this one out. The value I'm providing for that field is known to be unique, but the SQL Server spits it out each time.

Is there a way to have the ID primary field automatically update with a new value when a new record is generated? This is how I used to do it in Access, but cannot find a similar feature in SQL Server. I'm sure I'm missing something simple, but right now I'm stuck in this "Catch-22" situation.

Please help!

View 5 Replies View Related

Unique Constraint Doesn't Allow Multiple Null Values In Server?

Jun 2, 2014

Why we the Unique Constraint doesn't allow the multiple null values in Sql Server?

View 2 Replies View Related

Identity Fields As Primary Key In Server 7.0

May 13, 1999

Most of the tables in my database are implemented with IDENTITY columns as the primary key.
When an INSERT from my application is attempted, sometimes I get an error returned stating that insert
cannot be done because of duplicate key value. If I try the INSERT again, sometimes it works(??). Of course,
DBCC CHECKIDENT resets the identity value if trying the INSERT again doesn't work. Then sometime a little later, the problem happens again.
Is there anything I can do other than placing into my application code the execution of dbcc checkident
anytime I want to do an insert to prevent the error? By the way, DBCC CHECKDB revealed no problems.

HELP!

View 3 Replies View Related







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