Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    MS SQL Server


SuperbHosting.net have generously sponsored dedicated servers to ensure a reliable and scalable dedicated hosting solution for BigResource.com.





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


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 Complete Forum Thread with Replies

Related Forum Messages:
SP Causes The Error Violation Of UNIQUE KEY Constraint Cannot Insert Duplicate Key
 

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 Replies !
Violation Of PRIMARY KEY Constraint 'PK_tblType'. Cannot Insert Duplicate Key In Object 'dbo.tblType'.
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 Replies !
Catching Violation Of UNIQUE KEY Constraint In Stored Procedure
Dear All,

I have a stored procedure which bulk inserts records into a table based on a passed in variable that contains comma separated values of record Ids.

However I have a constraint on the table ensuring that value-pairs in 2 columns must be unique (as a person can not be twice on the same project)

Since I insert the passed in person Ids in a loop, I’d like to catch if this constraint has been violated and skip that specific cycle if it has but do commit the rest.

Not sure if this can be done, and if yes could someone let me know the SQL syntax and structure please?

Am I explaining this clearly?

Thanks in advance all comments are much appreciated!

View Replies !
Unique Constraint Violation On Single Cell Dataset
Hi,

 

I'm retreiving data from a SAP BW data source.  In the dataset designer I can build a query that returns a single value, the data returns successfully in the designer.  When I switch to the layout mode I can place the field of the datset in table / matrix / textbox.  However when i switch to preview mode or deploy the report and try to see them in Report Manager the report fails to render with the following message:

 

Query Execution Failed for dataset 'XXX'

These columns don't currently have unique values.

 

Its a single cell datset?!?!

 

I can successfully retreive data from other SAP Infocubes and queries.  I also cannot replicate the error using a SQL Server datasource.  The stack trace error looks like this:

 
w3wp!processing!6!5/9/2007-16:57:41:: e ERROR: Throwing Microsoft.ReportingServices.ReportProcessing.ReportProcessingException: Query execution failed for data set 'DataSet1'., ;
 Info: Microsoft.ReportingServices.ReportProcessing.ReportProcessingException: Query execution failed for data set 'DataSet1'. ---> System.ArgumentException: These columns don't currently have unique values.
   at System.Data.ConstraintCollection.AddUniqueConstraint(UniqueConstraint constraint)
   at System.Data.ConstraintCollection.Add(Constraint constraint, Boolean addUniqueWhenAddingForeign)
   at System.Data.DataTable.set_PrimaryKey(DataColumn[] value)
   at Microsoft.ReportingServices.XmlaClient.CubeMetadataCache.CreatePrimaryKeys(DataTable table, InternalObjectType objectType)
   at Microsoft.ReportingServices.XmlaClient.CubeMetadataCache.Populate(InternalObjectType objectType)
   at Microsoft.ReportingServices.XmlaClient.CubeMetadataCache.Microsoft.ReportingServices.XmlaClient.IMetadataCache.Populate(InternalObjectType objectType)
   at Microsoft.ReportingServices.XmlaClient.ObjectMetadataCache.Microsoft.ReportingServices.XmlaClient.IObjectCache.Populate()
   at Microsoft.ReportingServices.XmlaClient.CacheBasedFilteredCollection.PopulateCollection()
   at Microsoft.ReportingServices.XmlaClient.DimensionPropertyCollectionInternal.Find(String index)
   at Microsoft.ReportingServices.XmlaClient.DimensionPropertyCollection.Find(String index)
   at Microsoft.ReportingServices.DataExtensions.SapBw.DataReader.FindOptionalPropertyName(String internalColumnName, CubeDef cube, Boolean fIsYukonSP1)
   at Microsoft.ReportingServices.DataExtensions.SapBw.DataReader.GenerateColumnInformation(CubeDef cube, Boolean fIsYukonSP1)
   at Microsoft.ReportingServices.DataExtensions.SapBw.DataReader..ctor(AdomdDataReader dataReader, CubeDef cube)
   at Microsoft.ReportingServices.DataExtensions.SapBw.SapBwCommand.ExecuteReader(CommandBehavior behavior)
   at Microsoft.ReportingServices.ReportProcessing.ReportProcessing.RuntimeDataSetNode.RunDataSetQuery()

 

 

Any ideas why this happening and how I can get around it?

 

Thanks

 

 

Sanjay

 

ps Why would you want to put a unique constraint on a read only single table dataset?

View Replies !
Unique Constraint Does Not Permit Duplicate NULL Values
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 Replies !
Violation Of PRIMARY KEY Constraint Error
We are using web application, our server log this type error. some can help me out how to slove this type of error


4/16/2007 2:44:26 PM DECIMonitoring.DocTracking.Db:insertState [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]Violation of PRIMARY KEY constraint 'idx_edcstate_p_cl_01'. Cannot insert duplicate key in object 'tbl_edc_state'. tech.deci.com:5555

4/16/2007 2:44:26 PM DECIMonitoring.DocTracking.Db:insertState [ADA.1.316] Cannot execute the SQL statement "INSERT INTO db_webmethods_support_edc.dbo.tbl_edc_state(stat_s tate_id, state_item_id, state_start_ts) VALUES (?, ?, ?)". "

(23000/2627) [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]Violation of PRIMARY KEY constraint 'idx_edcstate_p_cl_01'. Cannot insert duplicate key in object 'tbl_edc_state'.

(HY000/3621) [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]The statement has been terminated."

[Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]Violation of PRIMARY KEY constraint 'idx_edcstate_p_cl_01'. Cannot insert duplicate key in object 'tbl_edc_state'. tech.deci.com:5555

4/16/2007 2:44:26 PM DECIMonitoring.DocTracking.Db:insertState [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]Violation of PRIMARY KEY constraint 'idx_edcstate_p_cl_01'. Cannot insert duplicate key in object 'tbl_edc_state'. tech.deci.com:5555

View Replies !
Error Number For Duplicate Column Value During An Insert For A Unique Column ?
I have a table in which a non-primary key column has a unique index on it.
If I am inserting a record into this table with a duplicate column value for the indexed column, then what will be the error number of the error in above scenario? OR How could I find this out?
 

View Replies !
Unique Constraint Error When There Is No Constraint
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 Replies !
Cannot Insert Duplicate Key Row In Object 'MSmerge_genhistory' With Unique Index 'unc1MSmerge_genhistory'
I have 1 client who keeps running into the following error on the subscriber and merge agents >
 
€œCannot insert duplicate key row in object 'MSmerge_genhistory' with unique index 'unc1MSmerge_genhistory'.€?
 
Last time we got this error I ran a reindex on table MSmerge_genhistory on the publisher database, I then successfully generated a new snapshot and the subscribers started to synchronize again.  This time around I keep getting the error even after I follow these steps (I also ran all the jobs to clean up replication).  The last time I ran into this error I created a job to reindex msmerge_genhistory on a nightly bases in an effort to avoid this problem.  Can somebody please provide me with a workaround and also the reason why this error occurs in the first place.
 
Thank you in advanced,
Pauly C
 

View Replies !
Cannot Insert Duplicate Key Row In Object 'dbo.lastlogin' With Unique Index 'IX_lastlogin'.
Hi.

I have been recently redesigning my tables - creating FK
relationships from child tables to the PK userid in the Users table.
The specifics of what I did and why can be seen here:

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1968856&SiteID=1

But, now I am getting the below error:

Cannot insert duplicate key row in object 'dbo.lastlogin' with unique index 'IX_lastlogin'.
The statement has been terminated.

Or, for that matter, SavedSearches or any other table where I need to
insert the same userid twice. I can see why I would want to avoid duplicates in the Users table. But, for lastlogin, savedsearches, and
a few of my other tables, the same user may account for multiple rows.

Any suggestions as to where I messed up and how to deal with this?

Thanks.


DBO.USERS






Code Snippet

CREATE TABLE [dbo].[users](
    [userid] [int] IDENTITY(1,1) NOT NULL,
    [lastname] [varchar](50) NULL,
    [firstname] [varchar](50) NULL,
    [email] [varchar](50) NOT NULL,
    [alternateemail] [varchar](50) NULL,
    [password] [varchar](50) NOT NULL,
    [role] [varchar](10) NOT NULL,
    [securityquestion] [varchar](50) NOT NULL,
    [securityanswer] [varchar](50) NOT NULL,
    [zipcode] [int] NOT NULL,
    [birthmonth] [tinyint] NOT NULL,
    [birthday] [tinyint] NOT NULL,
    [birthyear] [int] NOT NULL,
    [gender] [varchar](10) NULL,
    [city] [varchar](50) NULL,
    [state] [varchar](50) NULL,
    [country] [varchar](50) NULL,
    [registerdate] [datetime] NOT NULL,
    [editdate] [datetime] NULL,
    [confirmed] [bit] NULL CONSTRAINT [DF__Users__confirmed__4CC05EF3]  DEFAULT ((0)),
 CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED
(
    [userid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
 CONSTRAINT [IX_email] UNIQUE NONCLUSTERED
(
    [email] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF


/****** Object:  Table [dbo].[lastlogin]    Script Date: 08/22/2007 14:16:16 ******/
SET ANSI_NULLS ON


DBO.SAVEDSEARCHES


CREATE TABLE [dbo].[savedsearches](
    [savedsearchesid] [int] IDENTITY(1,1) NOT NULL,
    [searchname] [varchar](50) NOT NULL,
    [userid] [int] NOT NULL,
    [date] [datetime] NULL,
    [isdefault] [bit] NULL,
    [gender] [char](10) NULL,
    [startyear] [varchar](50) NULL,
    [endyear] [varchar](50) NULL,
    [country] [varchar](50) NULL,
    [miles] [int] NULL,
    [pictures] [varchar](50) NULL,
    [postal] [int] NULL,
    [sort] [tinyint] NULL,
    [photostring] [varchar](50) NULL,
    [orderby] [tinyint] NULL,
 CONSTRAINT [PK_SavedSearches] PRIMARY KEY CLUSTERED
(
    [userid] ASC,
    [searchname] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[savedsearches]  WITH NOCHECK ADD  CONSTRAINT [FK_savedsearches_users] FOREIGN KEY([userid])
REFERENCES [dbo].[users] ([userid])
GO
ALTER TABLE [dbo].[savedsearches] CHECK CONSTRAINT [FK_savedsearches_users]
GO
SET QUOTED_IDENTIFIER ON
GO




The following insert statement returned the error in the subject because userid = 32 already exists in the Users table.

INSERT INTO lastlogin
VALUES (32, CONVERT(VARCHAR(26), GETDATE(), 109), 1, CONVERT(VARCHAR(26), GETDATE(), 109))

DBO.LASTLOGIN





Code Snippet


CREATE TABLE [dbo].[lastlogin](
    [lastloginid] [int] IDENTITY(1,1) NOT NULL,
    [userid] [int] NOT NULL,
    [date] [datetime] NOT NULL,
    [status] [bit] NOT NULL CONSTRAINT [DF_lastlogin_status]  DEFAULT ((0)),
    [activity] [datetime] NOT NULL CONSTRAINT [DF_lastlogin_activity]  DEFAULT (getutcdate()),
    [online]  AS (case when [status]=(1) AND datediff(minute,[activity],getutcdate())<(30) then (1) else (0) end),
 CONSTRAINT [PK_lastlogin] PRIMARY KEY CLUSTERED
(
    [date] ASC,
    [userid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
ALTER TABLE [dbo].[lastlogin]  WITH NOCHECK ADD  CONSTRAINT [FK_lastlogin_users] FOREIGN KEY([userid])
REFERENCES [dbo].[users] ([userid])
GO
ALTER TABLE [dbo].[lastlogin] CHECK CONSTRAINT [FK_lastlogin_users]

View Replies !
Cannot Insert Duplicate Key Row In Object 'dbo.blabla..' With Unique Index 'Idx_blablabl'. The Statement Has Been Terminated. At
We are developing a project that is expected to hold TB of data and the back end used is SQL Server 2005.

I have the following problem

I have applied Nonclustered index over a column on a table.

Designed a SP for insertion which caters for updation incase the criteria based on the input is met.

The logic goes like this

Incase there exists a row containing the value of the column that is indexed for uniqueness, there should be updation. If not there should be a new row created.

 

However often there is an error message that is placed above.  This happens only on some of the SPs and only on rare occasions.

Can any body tell me if there is any problem with the SQL Server 2005

 

 

 

Thanks in advance

R Suresh, SQLDBA

 

 

 

 

View Replies !
Stuck Between &"Cannot Insert The Value NULL Into Column 'ID'&" And &"Violation Of PRIMARY KEY Constraint&"
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 Replies !
Catching Primary Key Violation On Insert Error
I've read a few different articticles wrt how the handle this error gracefully. I am thinking of wrapping my sql insert statement in a try catch  and have the catch be something likeIF ( e.ToString() LIKE '% System.Data.SqlClient.SqlException:
Violation of PRIMARY KEY constraint 'PK_PS_HR_Hrs'. Cannot insert duplicate key
in object %'){lable1.text = "Sorry, you already have reported hours for that day, please select anothe rdate" } Is there a better way?TIA Dan 

View Replies !
Unique Constraint Vs Unique Index In MS SQL 2000
HelloWhat should I use for better perfomance sinceunique constraint always use index ?ThanksKamil

View Replies !
What Is The Difference Between A UNIQUE INDEX And A UNIQUE CONSTRAINT?
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 Replies !
Unique Constraint And Unique Index, What's The Difference?
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 Replies !
Violation Of PRIMARY KEY Constraint
Hi,
I am trying to insert into a table. I got the above error message then I deleted all the data in the table. But I am still getting this error.

Whats wrong?

View Replies !
Violation Of PRIMARY KEY Constraint
I know what this error means is that you can not insert duplicate primary keys in the table but the thing is I am checking the rows if they do not exist then insert otherwise don't do any thing these are the lines I am writing in my strored procedure can someone please let me know what I am doing wrong here.

If not exists
(Select * From GGP WHERE
FFECTIVE_DATE =@v_EFFECTIVE_DATE AND
ASSET_ID= @v_ASSET_ID AND
ASSET_TYPE = @v_ASSET_TYPE AND
Value = @v_Value AND
hour = @v_Hour)

INSERT INTO GGP
(ASSET_ID,ASSET_TYPE,Hour,Value,EFFECTIVE_DATE) values(@v_ASSET_ID,@v_ASSET_TYPE,@v_Hour,@v_Value, @v_EFFECTIVE_DATE)



The exact error is
Violation of PRIMARY KEY constraint 'PK_SP_GGP'. Cannot insert duplicate key in object

Thanks in advance.

View Replies !
Violation Of PRIMARY KEY Constraint
When I try to insert data into a table (let's just call it MyTable for this post), I suddenly get the following error.

Violation of PRIMARY KEY constraint 'PK_MyTable'. Cannot insert duplicate key in object 'MyTable'.

My table does have a primary key field named 'id', which is an auto-incrementing BIGINT. The last record I successfully inserted received 14 in the id field, so I'm assuming the database is trying to assign 15 to the next. Unfortunately, there is already a record with an id of 15; the next available id is 21.

Is there a way to avoid these primary key collisions?

View Replies !
Violation Of Primary Key Constraint
 
Hi,
 
I've a set of source tables on one server and a set of destination tables on another. I'm moving this using a data flow task.
When I move data from one server to next, I get an error saying "Violation of Primary Key Constraint". This happens for only one table among the 6 tables that I have. I dont understand why it throws me this error. Though theres an error for this table, the data from source table moves into this destination table.
 
Am I missing something?
 
 
Thanks,
Subha Fernando

View Replies !
'check Constraint' Ignored - PK Violation
I thought the whole point of 'check constraint' being unticked meant you could whack your data straight in no probs.

How can I insert a bunch of historical information where I want to control the PK, in this case DealID?

I have got 'keep identity' checked.

I check the db, the Id does NOT exist currently.


Error: 0xC0202009 at Data Cleansing, Deal Insert [12194]: SSIS Error Code DTS_E_OLEDBERROR.  An OLE DB error has occurred. Error code: 0x80004005.
An OLE DB record is available.  Source: "Microsoft SQL Native Client"  Hresult: 0x80004005  Description: "The statement has been terminated.".
An OLE DB record is available.  Source: "Microsoft SQL Native Client"  Hresult: 0x80004005  Description: "Violation of PRIMARY KEY constraint 'PK_DealID'. Cannot insert duplicate key in object 'dbo.Deal'.".

View Replies !
Violation Of Primary Key Constraint
When replication merge, is taking place between two servers on one particular table I keep getting violation of primary key constraint, Does anyone out there have a fix for this?

View Replies !
Violation Of Primary Key Constraint
Hi,
 
I've a set of source tables on one server and a set of destination tables on another.
When I move data from one server to next, I get an error saying "Violation of Primary Key Constraint". This happens for only one table among the 6 tables that I have. I dont understand why it throws me this error. Though theres an error for this table, the data from source table moves into this destination table.
 
Am I missing something?
 
 
Thanks,
Subha Fernando
 

View Replies !
VIOLATION OF PRIMARY KEY CONSTRAINT
Violation of PRIMARY KEY constraint 'PK_tbl_others. Cannot insert duplicate key in object 'tbl_others.
The statement has been terminated.-- What does it mean i cant load the data to tbl_others

View Replies !
Violation Of Primary Key Constraint
I'm trying to insert records into a table and getting the below error and not sure how to resolve it:

Server: Msg 2627, Level 14, State 1, Line 1
Violation of PRIMARY KEY constraint 'PK_propertyItem'. Cannot insert duplicate key in object 'propertyItem'.
The statement has been terminated.

View Replies !
Cannot INSERT Data To 3 Tables Linked With Relationship (INSERT Statement Conflicted With The FOREIGN KEY Constraint Error)
Hello
 I have a problem with setting relations properly when inserting data using adonet. Already have searched for a solutions, still not finding a mistake...
Here's the sql management studio diagram :

 and here goes the  code1 DataSet ds = new DataSet();
2
3 SqlDataAdapter myCommand1 = new SqlDataAdapter("select * from SurveyTemplate", myConnection);
4 SqlCommandBuilder cb = new SqlCommandBuilder(myCommand1);
5 myCommand1.FillSchema(ds, SchemaType.Source);
6 DataTable pTable = ds.Tables["Table"];
7 pTable.TableName = "SurveyTemplate";
8 myCommand1.InsertCommand = cb.GetInsertCommand();
9 myCommand1.InsertCommand.Connection = myConnection;
10
11 SqlDataAdapter myCommand2 = new SqlDataAdapter("select * from Question", myConnection);
12 cb = new SqlCommandBuilder(myCommand2);
13 myCommand2.FillSchema(ds, SchemaType.Source);
14 pTable = ds.Tables["Table"];
15 pTable.TableName = "Question";
16 myCommand2.InsertCommand = cb.GetInsertCommand();
17 myCommand2.InsertCommand.Connection = myConnection;
18
19 SqlDataAdapter myCommand3 = new SqlDataAdapter("select * from Possible_Answer", myConnection);
20 cb = new SqlCommandBuilder(myCommand3);
21 myCommand3.FillSchema(ds, SchemaType.Source);
22 pTable = ds.Tables["Table"];
23 pTable.TableName = "Possible_Answer";
24 myCommand3.InsertCommand = cb.GetInsertCommand();
25 myCommand3.InsertCommand.Connection = myConnection;
26
27 ds.Relations.Add(new DataRelation("FK_Question_SurveyTemplate", ds.Tables["SurveyTemplate"].Columns["id"], ds.Tables["Question"].Columns["surveyTemplateID"]));
28 ds.Relations.Add(new DataRelation("FK_Possible_Answer_Question", ds.Tables["Question"].Columns["id"], ds.Tables["Possible_Answer"].Columns["questionID"]));
29
30 DataRow dr = ds.Tables["SurveyTemplate"].NewRow();
31 dr["name"] = o[0];
32 dr["description"] = o[1];
33 dr["active"] = 1;
34 ds.Tables["SurveyTemplate"].Rows.Add(dr);
35
36 DataRow dr1 = ds.Tables["Question"].NewRow();
37 dr1["questionIndex"] = 1;
38 dr1["questionContent"] = "q1";
39 dr1.SetParentRow(dr);
40 ds.Tables["Question"].Rows.Add(dr1);
41
42 DataRow dr2 = ds.Tables["Possible_Answer"].NewRow();
43 dr2["answerIndex"] = 1;
44 dr2["answerContent"] = "a11";
45 dr2.SetParentRow(dr1);
46 ds.Tables["Possible_Answer"].Rows.Add(dr2);
47
48 dr1 = ds.Tables["Question"].NewRow();
49 dr1["questionIndex"] = 2;
50 dr1["questionContent"] = "q2";
51 dr1.SetParentRow(dr);
52 ds.Tables["Question"].Rows.Add(dr1);
53
54 dr2 = ds.Tables["Possible_Answer"].NewRow();
55 dr2["answerIndex"] = 1;
56 dr2["answerContent"] = "a21";
57 dr2.SetParentRow(dr1);
58 ds.Tables["Possible_Answer"].Rows.Add(dr2);
59
60 dr2 = ds.Tables["Possible_Answer"].NewRow();
61 dr2["answerIndex"] = 2;
62 dr2["answerContent"] = "a22";
63 dr2.SetParentRow(dr1);
64 ds.Tables["Possible_Answer"].Rows.Add(dr2);
65
66 myCommand1.Update(ds,"SurveyTemplate");
67 myCommand2.Update(ds, "Question");
68 myCommand3.Update(ds, "Possible_Answer");
69 ds.AcceptChanges();
70

and that causes (at line 67):"The INSERT statement conflicted with the FOREIGN KEY constraint
"FK_Question_SurveyTemplate". The conflict occurred in database
"ankietyzacja", table "dbo.SurveyTemplate", column
'id'.
The statement has been terminated.
at System.Data.Common.DbDataAdapter.UpdatedRowStatusErrors(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, Int32 commandCount)
at System.Data.Common.DbDataAdapter.UpdatedRowStatus(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, Int32 commandCount)
at System.Data.Common.DbDataAdapter.Update(DataRow[] dataRows, DataTableMapping tableMapping)
at System.Data.Common.DbDataAdapter.UpdateFromDataTable(DataTable dataTable, DataTableMapping tableMapping)
at System.Data.Common.DbDataAdapter.Update(DataSet dataSet, String srcTable)
at AnkietyzacjaWebService.Service1.createSurveyTemplate(Object[] o) in J:\PL\PAI\AnkietyzacjaWebService\AnkietyzacjaWebServicece\Service1.asmx.cs:line 397"


Could You please tell me what am I missing here ?
Thanks a lot.
 

View Replies !
Violation Of Primary Key Constraint PK_Notelist
I am running merg replication (pull) between 7 various sites and once in a while when two people update information in a table in close proximty in time,  I will get a primary key violation when viewing conflicts, it's almost excluslively in one table.  What is the best way to handle this error.  Should I delete the entire column on the subscriber and let the publisher update the subscriber?  Or should I redesing the table and primary keys?  Any assistance in the matter would be greatly appreciated.

View Replies !
Errror Message: Violation Of PRIMARY KEY Constraint...
Hello!

We have a problem that occurs irregularly in SQL-Server 6.5.
An Error occurs when trying to insert a record. The keyfield of the table is AUTONUMBER.


Run-time error...:
"Violation of PRIMARY KEY Constraint aaaaa_TableName_PK
Attemp to insert dublicate key in object 'TableName'

I hope none has seen this error it's...

thanks,

J. Kiiskinen

View Replies !
Unique Constraint Vs Unique Index
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 Replies !
Unique Index Vs Unique Constraint
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 Replies !
Does SQL Server Check For Constraint Violation When COMMIT Is Called?
If there are two different transactions, both of which update the username column to 'xyz' for userid = 234 in 'Users' table. This is a unique value for username.  Ater this update each transaction adds a row to 'AppLog' table. The transaction is only committed after second operation.
The 'username' column has a unique constraint on it.
If transaction isolation level is 'read committed', and both transaction execute the first operation when neither of the transactions have been committed, then the transaction that calls COMMIT later will error out or not? If COMMIT does not check constraints then it will NOT error out. As a result we will have a violation of unique constraint happening without any error being thrown by SQL Server.

View Replies !
Oracle 9i -&&> SQL Server 2005: Violation Of PRIMARY KEY Constraint
Hi there,

When the distribution agent runs trying to apply the snapshot at the subscriber I get the following error message

Message
2006-06-24 12:41:59.216 Category:NULL
Source:  Microsoft SQL Native Client
Number: 
Message: Batch send failed
2006-06-24 12:41:59.216 Category:NULL
Source:  Microsoft SQL Native Client
Number:  2627
Message: Violation of PRIMARY KEY constraint 'MSHREPL_1_PK'. Cannot insert duplicate key in object 'dbo.ITEMTRANSLATION'.
2006-06-24 12:41:59.216 Category:NULL
Source: 
Number:  20253

What could possibly cause this error? And how can I possibly fix it?

Best regards,

JB

View Replies !
Error Message On Attempted Duplicate Insert
Hi All,  I have a web form that inserts information into two tables in sql 2005 database on a submit button click.  I have a unique key on the tables preventing duplicate information which works fine.  The problem I have is that at the minute if a users tries to insert a duplicate row they just get the built in sql error message.  Is there a way I can validate the information before if goes into the database and display perhaps a label telling the user of their error or is there a way I can customize the build in sql error message?  I've had a search on various forums and sites and can't find any info that would help me. Thanks in advance
 Dave   

View Replies !
'Cannot Insert Duplicate Key' Error With Identity Column As PK
 

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 Replies !
Add UNIQUE Constraint
Hi,I want to add unique contraint to EXISTING column in EXISTING table.I have ms sql 2005.How to do that?

View Replies !
Unique Constraint
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 Replies !
Unique Constraint
Does anyone have any Idea on how I could enforce a unique constrait across multiple tables?

View Replies !
PK -vs- Unique Constraint
When creating a PRIMARY KEY Unique constraint on a table an Index is created automatically.

However, when creating a UNIQUE Index a constraint is not automatically created.


I'm wondering why I would choose to use a constraint -vs- UNIQUE INDEX

Any input...?? The results are the same aren't they??

Dano

View Replies !
Constraint Unique Row
 

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

View Replies !
Unique Constraint
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 Replies !
Unique Constraint
Anybody knows how to make two columns in a table unique?

View Replies !
UNIQUE Constraint
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 Replies !
A Unique Unique Constraint
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 Replies !
Bulk Insert, Skip Rows With Duplicate Key Error?
Does sql server have a way to handle errors in a sproc which would allowone to insert rows, ignoring rows which would create a duplicate keyviolation? I know if one loops one can handle the error on a row by rowbasis. But is there a way to skip the loop and do it as a bulk insert?It's easy to do in Access, but I'm curious to know if SQL Server propercan handle like this. I am guessing that a looping operation would beslower to execute?

View Replies !
Sql Exception Unique Key Constraint
 
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 Replies !
Unique Constraint On Two Tables?
Is it possible to create a unique constraint on two tables?In mssql2000?

View Replies !
Syntax For UNIQUE Constraint
I have an existing table:CREATE TABLE TestQuestions (qIdintNOT NULLIDENTITY(1,1)CONSTRAINTPK_TestQuestions PRIMARY KEY NONCLUSTERED,testIdintNOT NULLREFERENCESTests(testId)ON DELETE CASCADE,objectiveIdvarchar(30)NULLqTypeintNOT NULLCONSTRAINTDF_TestQuestions_qType DEFAULT (0),)And I'd like to add the constraint:ALTER TABLE TestQuestions ALTER COLUMN objectiveIdCONSTRAINT U_TestQuestions UNIQUE NONCLUSTERED (testId, objectiveId)Although obviously that's not the correct syntax. Could you tell mewhat *is* the correct syntax?Thanks,-- Rick

View Replies !
Unique Constraint Index
When I add a unique key constraint to column in SQL 6.5 why does it alsocreate an index. e.g. In the table subaccounts I added a unique keyconstraint for the column login and SQL creates an index with the nameUQ_SubAccounts_2__19 (UKC).Does this also mean that there is no need to create an index for thiscolumn?thxMansoor

View Replies !
Unique Constraint/index
I'm trying to weight the pros and cons of unique constraints and unique indexes. I understand that creating a unique constraint also creates an index. If that is the case, why not just use a unique index? Could someone give me an example of when you would want an unique constraint over an unique indexes

Thanks in advance

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

thanks

View Replies !
Unique Constraint With Conditioning?
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 Replies !

Copyright © 2005-08 www.BigResource.com, All rights reserved