Deployment errors, "There is already an object named 'PK_***' in the database. Could not create constraint." - sql

When I try to run my app, I get the following errors:
There is already an object named 'PK_***' in the database. Could not create constraint."
That's actually two errors combined for brevity. Note: the asterisks are my own; that is not the actual name of the key.
I've scoured what seems like every post on here, but I can't seem to get any further in finding a solution. The worst part? No one else in the team is experiencing these errors when they run, nor can they determine why I am. We are all using the same environment, VS 2012 Premium RC. I certainly have latest from TFS.
I am wondering if anyone else has come across an issue similar to this where the problems/errors occurred in only one person's environment? I can continue and run the app. It seems to run as expected, but I am the only one getting those errors.

In SQL Server constraints such as primary keys or foreign keys are objects in their own right, even though they are dependent upon the "containing" table.
That means that their names must be unique within the owning schema. So, just as executing DDL along the lines of
create table some_schema.foo
(
id int not null
)
go
create table some_schema.foo
(
id int not null
)
go
will raise an error when the second create table is [attempted to be] executed, executing ddl like this will likewise raise an error:
create table some_schema.foo
(
id int not null ,
description varchar(200) not null ,
constraint PK primary key clustered ( id ) ,
constraint AK01 unique nonclustered ( description ) ,
)
go
create table some_schema.bar
(
id int not null ,
description varchar(200) not null ,
constraint PK primary key clustered ( id ) ,
constraint AK01 unique nonclustered ( description ) ,
)
go
will likewise raise an error as the constraint that you're trying to create have duplicate names. You need to qualify them with the table name, thusly:
create table some_schema.foo
(
id int not null ,
description varchar(200) not null ,
constraint foo_PK primary key clustered ( id ) ,
constraint foo_AK01 unique nonclustered ( description ) ,
)
go
create table some_schema.bar
(
id int not null ,
description varchar(200) not null ,
constraint bar_PK primary key clustered ( id ) ,
constraint bar_AK01 unique nonclustered ( description ) ,
)
go
and you problem will go away.
It does seem to me that dependent objects that don't exist outside the context of an owing object should be namespaced within the owning object's scope, but that's not the way the SQL standard works.
Good luck!

Related

Can we use foreign key as primary key along with another attribute as below?

I have to create this project for one of my assignments and I have to use Transact-SQL to create this database. I have changed this below code many times to avoid this error but its still keep coming and can't think of any reason for this.
CREATE TABLE Job
(
Job_ID INT NOT NULL IDENTITY (500, 1),
Pickup_Address VARCHAR(255),
Destination_Address VARCHAR(255),
Crew_Name VARCHAR(255),
Customer_Name VARCHAR(255),
PRIMARY KEY(Job_ID)
)
GO
INSERT INTO Job(Pickup_Address,Destination_Address,Crew_Name,Customer_Name)
VALUES ('Ceylinco Centre Building, 3rd Floor, Nawam Mawatha','NO.50, Sumanagala Road,Rathmalana','Maharagama Crew 1','Dilan'),
('3/82, ST.JUDE LANE,Dalugama','19A, 4th Lane,Koswatthe Rd','Maharagama Crew 2','Kasun'),
('19 Saunders Place,Colombo 12','54/3, Elapitiwala,Ragama','Kottawa Crew 1','Kelly'),
('381 Prince of Wales Avenue,Colombo 14','51, SEA STREET,Colombo','Kottawa Crew 2','Kasun'),
('250 Galle Road,Colombo 03','34, Pepiliyana Road,Nugegoda','Nugegoda Crew 2','Alan')
GO
CREATE TABLE Loads
(
Load_ID INT NOT NULL IDENTITY (1, 1),
Job_ID INT NOT NULL FOREIGN KEY REFERENCES Job(Job_ID),
Load_Type VARCHAR(255),
Product_Name VARCHAR(255),
Loaded_Time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
PRIMARY KEY (Load_ID, Job_ID),
)
GO
I have executed the above SQL code, previously I couldn't create the Loads table and got an error
Invalid referencing table
After I tried to avoid this now it can be executed although there is an error and it's in below. what I need to know is the reason for this and will it be a problem if I keep this as it is. Thank you
Foreign key 'FK_Loads_c6b32eef601ef719ed3' References invalid table 'job'
The code works, you may have the case sensitive collation. To know the collation you can run this code:
SELECT SERVERPROPERTY('collation');
If this is the case, you can change it (2008 or higher, except azure) with code like the following (adding the desired collation):
ALTER DATABASE YOURS_DATABASE
COLLATE Modern_Spanish_CS_AS ;
more information here here

How do I select insert into select a table which already has values in the primary key column without adding new rows?

I'm working on a database for my school project in which I have to produce a functional database by normalizing sample tables given to us.
One table I'm having trouble with is itineraries. I produce 3 tables from the normalization which are "Destinations", "Itineraries" and "Itinerary_Destinations".
The code for Destinations is:
create table Destinations
(
DestinationID varchar(5) primary key,
Name varchar(45)
);
The code for Itineraries is:
create table Itineraries
(
ItineraryID varchar(5),
Name varchar(45)
);
The code for the last table is:
create table Itinerary_Destinations
(
DI varchar(5) primary key,
ItineraryID varchar(5) foreign key references Itineraries(ItineraryID),
Itinerary_Name varchar(45),
DestinationID varchar(5) foreign key references Destinations(DestinationID),
Destination_Name varchar(45)
);
Data has already been inserted into all 3 tables with the exception of 'Destination_Name' and 'Itinerary_Name' columns. The code I'm attempting to use is returning as error. The code is shown below.
insert into Itinerary_Destinations (Itinerary_name)
select Name from Itineraries where
Itineraries.ItineraryID = ItineraryID;
The error it returns is
Msg 515, Level 16, State 2, Line 1 Cannot insert the value NULL into
column 'DI', table 'DDDAssignment.dbo.Itinerary_Destinations'; column
does not allow nulls. INSERT fails. The statement has been terminated.
Is there a method to accomplish the task of inserting the Destination_Name and Itinerary_Name without creating new records that require primary keys?
Or should I do it manually?
If you want to modify records which already exist, then you should be using an UPDATE rather than an INSERT:
UPDATE a
SET Itinerary_name = b.Name
FROM Itinerary_Destinations a
INNER JOIN Itinerary_name b
ON a.ItineraryID = b.ItineraryID;
But, if you do have some data which is not already logically associated with the Itinerary_Destinations table, then using an insert is appropriate.
use coalesce funtion in case null it will insert blank string, as your column does not allow null value thats why you got that error in your query
insert into Itinerary_Destinations (Itinerary_name)
select coalesce(Name,' ') from Itineraries where
Itineraries.ItineraryID = ItineraryID;

How to use value generated by GENERATE_UNIQUE() function as foreign key?

I trying to implement the example from this manual Generating Unique Values in DB2 Universal Database but encountered the following problem.
I've two tables,
CREATE TABLE PC_LIST (
PC_ID CHAR(13) FOR BIT DATA NOT NULL,
PC_NAME VARCHAR(100) NOT NULL
PRIMARY KEY (ID)
);
And second table
CREATE TABLE PC_DATA (
ID CHAR(13) FOR BIT DATA NOT NULL,
PC_ID CHAR(13) FOR BIT DATA NOT NULL,
PC_NAME VARCHAR(100) NOT NULL
PRIMARY KEY (ID),
FOREIGN KEY (PC_ID) REFERENCES PC_LIST(PC_ID)
);
I add records to first table PC_LIST without any issues, and use inside INSERT query GENERATE_UNIQUE() function, everything works fine.
When I try to add a record to the second table and copy a value from PC_LIST.PC_ID as is I get an error Value "20150408131401000109000000 " is too long..
When I added a cast like following: CAST('20150408131401000109000000' AS CHAR(13) FOR BIT DATA) I get an error that The INSERT or UPDATE value of the FOREIGN KEY is not equal to any value of the parent key of the parent table.
What am I doing wrong?
Thank you.
UPDATE:
This code I use to insert data in PC_DATA
INSERT INTO PC_DATA
(
ID,
PC_ID,
PC_NAME
) VALUES (GENERATE_UNIQUE(), CAST('20150408131401000109000000' AS CHAR(13) FOR BIT DATA) ,'anatoly-pc');
Of course that PC_ID I've taken from PC_LIST table where it exists.

Beginner with triggers

Im a beginner in database and i got this difficult auction database project.
Im using SQL Server Management Studio also.
create table user(
name char(10) not null,
lastname char(10) not null
)
create table item(
buyer varchar(10) null,
seller varchar(10) not null,
startprice numeric(5) not null,
description char(22) not null,
start_date datetime not null,
end_date datetime not null,
seller char(10) not null,
item_nummer numeric(9) not null,
constraint fk_user foreign key (buyer) references user (name)
)
Basically what the rule im trying to make here is:
Column buyer has NULL unless the time (start_date and end_date) is over and startprice didnt go up or increased. Then column buyer will get the name from table user who bidded on the item.
The rule is a bid too difficult for me to make, i was thinking to make a trigger, but im not sure..
Your model is incorrect. First you need a table to store the bids. Then when the auction is over, you update the highest one as the winning bid. Proably the best way is to have a job that runs once a minute and finds the winners of any newly closed auctions.
A trigger will not work on the two tables you have because triggers only fire on insert/update or delete. It would not fire because the time is past. Further triggers are an advanced technique and a db beginner should avoid them as you can do horrendous damage with a badly written trigger.
You could have a trigger that works on insert to the bids table, that updates the bid to be the winner and takes that status away from the previous winner. Then you simply stop accepting new bids at the time the auction is over. Your application could show the bidder who is marked as the winner as the elader if the auction is till open and teh winner if it is closed.
There are some initial problems with your schema that need addressed before tackling your question. Here are changes I would make to significantly ease the implementation of the answer:
-- Added brackets around User b/c "user" is a reserved keyword
-- Added INT Identity PK to [User]
CREATE TABLE [user]
(
UserId INT NOT NULL
IDENTITY
PRIMARY KEY
, name CHAR(10) NOT NULL
, lastname CHAR(10) NOT NULL
)
/* changed item_nummer (I'm not sure what a nummer is...) to ItemId int not null identity primary key
Removed duplicate Seller columns and buyer column
Replaced buyer/seller columns with FK references to [User].UserId
Add currentBid to capture current bid
Added CurrentHighBidderId
Added WinningBidderId as computed column
*/
CREATE TABLE item
(
ItemId INT NOT NULL
IDENTITY
PRIMARY KEY
, SellerId INT NOT NULL
FOREIGN KEY REFERENCES [User] ( UserId )
, CurrentHighBidderId INT NULL
FOREIGN KEY REFERENCES [User] ( UserId )
, CurrentBid MONEY NOT NULL
, StartPrice NUMERIC(5) NOT NULL
, Description CHAR(22) NOT NULL
, StartDate DATETIME NOT NULL
, EndDate DATETIME NOT NULL
)
go
ALTER TABLE dbo.item ADD
WinningBidderId AS CASE WHEN EndDate < CURRENT_TIMESTAMP
AND currentBid > StartPrice THEN CurrentHighBidderId ELSE NULL END
GO
With the additional columns a computed column can return the correct information. If you must return the winner's name instead of id, then you could keep the schema above the same, add an additional column to store the user's name, populate it with a trigger and keep the computed column to conditionally show/not show the winner..

Primary key consists of a foreign key and a identity and should reset identity under a condition

create table Linq_TB
{
url_id int NOTNULL,
Pg_Name nvarchar(50) NOTNULL,
URL nvarchar(50) NUTNULL,
CONSTRAINT Linq_id PRIMARY KEY (url_id,DBCC Checkident(Linq_TB,RESEED,0) case url_id not in(select URL_Id from URL_TB ))
}
I want to make a table which it's primary key is Linq_id and gets it's value from both the url_id and identity with start from 1 and increments 1 by 1. url_id is a foreign key. For example if url_id is 1, linq_id's will be 11, 12, 13,... and I also want to reset linq_id identity when the url_id changes.
What should the query be? The query above doesn't work, why?
Thanks in advance
Well, a constraint contains conditions and not code to be executed. You should consider using a stored procedure for your task and also a homegrown method of assigning IDs.
However, it is not a common practice to have your primary keys 'pretty' or formatted, as there is no real benefit (except maybe for debugging purposes maybe).
I do not recommend executing DBCC whenever your url_ID changes. This has a great negative impact on performance.
Why don't you leave the IDs like they are?
You can do this with the following table and trigger definitions:
CREATE TABLE Linq_TB
(
url_id INT NOT NULL,
Linq_id INT NOT NULL,
Pg_Name NVARCHAR(50) NOT NULL,
URL NVARCHAR(50) NOT NULL,
CONSTRAINT PK_Link_TB PRIMARY KEY (url_id, Linq_id),
CONSTRAINT FK_URL_TB_URL_ID FOREIGN KEY (url_id) REFERENCES URL_TB (url_id)
)
GO
CREATE TRIGGER tr_Linq_TB_InsertUpdate
ON Linq_TB
INSTEAD OF INSERT
AS
INSERT INTO Linq_TB
SELECT i.url_id,
ISNULL(tb.Linq_id, 0)
+ row_number() over (partition by i.url_id order by (select 1)),
i.Pg_Name, i.URL
FROM inserted i
LEFT OUTER JOIN
(
SELECT url_id, MAX(Linq_ID) Linq_id
FROM Linq_TB
GROUP BY url_id
) tb ON i.url_id = tb.url_id
GO
The CREATE TABLE defines your columns and constraints. And, the trigger creates the logic to generate a sequence value in your Linq_id column for each url_id.
Note that the logic in the trigger is not complete. A couple of issues are not addressed: 1) If the url_id changes for a row, the trigger doesn't update the Link_id, and 2) deleting rows will lead to gaps in the Linq_TB column sequence.