0

I am trying to create and populate a new table from data within existing tables all within 1 procedure, but I keep getting an error about duplicate keys. This has to be done within 1 procedere file for it is for an assignment. I have already tried to use SELECT INTO to populate most_profitable but that did not work.

-- ================================================
-- Template generated from Template Explorer using:
-- Create Procedure (New Menu).SQL
--
-- Use the Specify Values for Template Parameters 
-- command (Ctrl-Shift-M) to fill in the parameter 
-- values below.
--
-- This block of comments will not be included in
-- the definition of the procedure.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Daniel McClure
-- Create date: 11/17/2014
-- Description: Calculates The Most Profitable Titles
-- =============================================
CREATE PROCEDURE MostProf   
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

CREATE TABLE dbo.most_profitable
(
pub_id char(4) NOT NULL,
profit money
PRIMARY KEY (pub_id)
);

INSERT INTO dbo.most_profitable
(
   titles.pub_id
)
SELECT
titles.pub_id 
FROM titles


END
GO

The error:

Violation of PRIMARY KEY constraint 'PK__most_pro__2515F222534D60F1'. Cannot insert duplicate key in object 'dbo.most_profitable'.

1 Answer 1

1

What this most likely means is that the original table has duplicates, that is, titles.pub_id is currently not a unique list. That is, you're trying to make it unique, and it is not.

To confirm this, run this query:

SELECT titles.pub_id, COUNT(*) As CountForPub
FROM titles
GROUP BY titles.pub_id
ORDER BY CountForPub DESC
LIMIT 20

If you see any pub_id's that have the count greater than 1, you know that you have duplicates.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! All I had to do was throw in a DISTINCT to avoid multiples!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.