【发布时间】:2016-03-08 11:21:36
【问题描述】:
我在尝试将 tempTable 中的行添加到表时遇到问题。问题是它会添加 TempDealer 表中的行,即使它们已经在 Dealership 表中(请注意,我在 WHERE 语句中指定 WHERE td.supplier_ref NOT IN (SELECT supplier_ref FROM @dealerStatus)。每次我运行存储过程它再次将 TempDealer 中的所有行添加到 Dealership 表中,而它应该只添加一次。有什么想法吗?提前致谢。
INSERT INTO @dealerStatus (dealerId, supplier_ref, [add], [timestamp])
SELECT NULL, td.supplier_ref, 1, GETDATE()
FROM TempDealer td
WHERE td.supplier_ref NOT IN (SELECT supplier_ref FROM @dealerStatus)
INSERT INTO Dealership(
dealership_name,
telephone,
fax,
sales_email,
support_email,
service_mask,
address1,
address2,
town,
county,
postcode,
website,
date_modified,
supplier_ref,
dealer_type,
county_id,
town_id,
area_id,
district_id,
longitude,
latitude
)
SELECT DISTINCT
[updateSource].leasing_broker_name,
[updateSource].telephone,
[updateSource].fax_number,
[updateSource].email,
[updateSource].support_email,
[updateSource].service_mask,
[updateSource].address1,
[updateSource].address2,
[updateSource].town,
[updateSource].county,
[updateSource].post_code,
[updateSource].web_address,
GETDATE(),
[updateSource].supplier_ref,
1,
[updateSource].county_id,
[updateSource].town_id,
[updateSource].region,
[updateSource].district,
[updateSource].longitude,
[updateSource].latitude
FROM
@dealerStatus dealerUpdateStatus INNER JOIN
TempDealer [updateSource] ON dealerUpdateStatus.supplier_ref = updateSource.supplier_ref
WHERE
dealerUpdateStatus.[add] = 1
【问题讨论】:
-
现在你说的是“从 TempDealer 中插入 (at)dealerStatus 的每一行,其中没有与 (at)dealerStatus 中已经存在的供应商参考匹配的供应商参考”。问题是当它检查这个时,(at)dealerStatus 是空的。我认为您需要将 WHERE 子句更改为 NOT IN (SELECT supplier_ref FROM Dealership)。
-
我做到了,它没有插入任何 WHERE td.supplier_ref NOT IN(从经销商处选择供应商参考)。说真的,这让我发疯,不可能那么复杂
-
很难弄清楚它出了什么问题,因为显然我不是在看桌子的人,但让我仔细看看。
-
我修好了!谢谢你的方向约翰克利福德你是对的,我必须从经销商表中选择供应商参考,因为我在@dealerStatus 中的插入从未发生之前拥有它;)
标签: sql insert sql-server-2012 add