我想知道是否有人可以帮助我使用下面的SQL代码。我试图将BC_completions表中的所有记录插入到我的Geodata表中。如果我在插入上排除ID列,我会得到一个'Msg 515 ...无法将值NULL插入列'ID'。但如果我将其包含在下面,我会得到一个'Msg ...违反PRIMARY KEY约束'。
更令人困惑的是,如果我手动输入我从@PK获得的值,数据库会接受它,所以这里的任何帮助都会很棒。
由于
DECLARE @PK AS INT
DECLARE @COUNT AS INT
DECLARE @RECORDCOUNT AS INT
SET @PK =
(SELECT TOP 1 ID FROM PRCORE.DBO.GEODATA
ORDER BY ID DESC)
SET @RECORDCOUNT =
(SELECT COUNT(*) FROM BC_COMPLETIONS)
SET @COUNT = 0
WHILE @COUNT < @RECORDCOUNT
BEGIN
SET @PK = @PK+1
SET @COUNT = @COUNT+1
INSERT INTO PRCORE.DBO.GEODATA
(ID,RecordType,ReferenceName,LocationDescription,Description,ORN,StartDate,ChgText)
SELECT @PK,189,REFVAL,ADDRESS,DSCRPN,ORN,RECPTD,AGTNAME
FROM BC_COMPLETIONS B
where @PK not in (select ID from prcore.dbo.geodata)
END
答案 0 :(得分:3)
这是循环和插入语句的WHERE约束的问题。您正在从BC_COMPLETIONS中选择所有记录并将它们分配给相同的PK。
相反,使用ROW_NUMBER()函数分配您的PK,这样您就可以一次完成所有操作,而不是一次只执行一条记录:
DECLARE @PK AS INT
DECLARE @RECORDCOUNT AS INT
SET @PK = (SELECT TOP 1 ID FROM PRCORE.DBO.GEODATA ORDER BY ID DESC) + 1
SET @RECORDCOUNT = (SELECT COUNT(*) FROM BC_COMPLETIONS)
INSERT INTO PRCORE.DBO.GEODATA (ID,RecordType,ReferenceName,LocationDescription,Description,ORN,StartDate,ChgText)
SELECT ROW_NUMBER() OVER(ORDER BY REFVAL) + @PK ,189,REFVAL,ADDRESS,DSCRPN,ORN,RECPTD,AGTNAME
FROM BC_COMPLETIONS B