使用现有数据创建新的SQL表

时间:2014-11-18 00:57:58

标签: sql-server

我正在尝试在1个过程中从现有表中的数据创建和填充新表,但我一直收到有关重复键的错误。这必须在1个procdere文件中完成,因为它是一个赋值。我已经尝试使用SELECT INTO来填充most_profitable,但这不起作用。

-- ================================================
-- 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

错误:

  

违反PRIMARY KEY约束' PK__most_pro__2515F222534D60F1'。无法在对象' dbo.most_profitable'。

中插入重复的密钥

1 个答案:

答案 0 :(得分:1)

这最有可能意味着原始表格有重复,即 titles.pub_id 目前不是唯一列表。也就是说,你试图让它独一无二,而事实并非如此。

要确认这一点,请运行此查询:

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

如果您看到任何计数大于1的pub_id,则表示您有重复项。