gpt4 book ai didi

sql - 插入表并跳过重复项

转载 作者:行者123 更新时间:2023-12-04 23:57:05 24 4
gpt4 key购买 nike

我的存储过程有 3 个我正在传递的参数 (@nameP, @idP, @dateP )
并将数据插入 #myTemp table

然后我用

 select * 
into dbo.realTable
from #myTemp

然后我想根据 dbo.FinalTable 过滤掉任何已经存在的数据(在 dateP 中)和 idP :
insert into dbo.FinalTable 
select * from dbo.realTable
where not exists (select * from dbo.FinalTable
where idP = @idP
and dateP = @dateP)

drop table dbo.realTable

当我执行我的程序时,数据被附加到表中。问题是,如果我把相同的 idP并为相同的 dateP 再次执行它,它不应该插入任何东西,但它确实插入了。我认为问题可能出在 insert into部分。

编辑:

如果我删除 and dateP = @dateP,这很有效来自 where 子句)
ps:谢谢大家的回答,即使在我的情况下我只需要做我上面写的,我从你的回答中学到了

最佳答案

这将插入 realtable do finaltable 中的所有行,其中 idP 和 dateP 的组合不存在......(使用简单的左连接):

INSERT INTO dbo.FinalTable 
SELECT *
FROM dbo.RealTable R
LEFT JOIN dbo.FinalTable T ON T.idP = R.idP
AND T.dateP = R.dateP
WHERE T.idP IS NULL

我强烈建议使用列名而不是“*”!!
INSERT INTO table (column1, column2)
SELECT column1, column2 FROM anothertable

关于sql - 插入表并跳过重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32819227/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com