访问查询以从另一个表中插入记录

时间:2017-09-07 18:00:18

标签: sql ms-access

我希望快速...我正在努力解决访问查询

我需要将表A 中的值复制到表B ,如果它们不存在于表中B 使用MTR#字段来确定是否存在。

插入时,查询还需要从前一条记录中增加tB.ImgRefNum

我需要复制

tA.MTR# to tB.MTR# 
tA.MTRF1 to tB.Item 
tA.MTRF2 to tB.PONum 
tA.MTRF3 to tB.DateRecv **BUT need to cast from text YYYYMMDD to date format)

Table A 
TRX Number (number) 
MTR#       (number) 
MTRF1      (text) 
MTRF2      (text) 
MTRF3      (text)   *A date is stored here but textually as YYYYMMDD

Table B 
ImgRefNum  (number) 
MTR#       (number)  
Item       (text) 
W          (number)
L          (number)
Vendor     (text)
PONum      (number)
DateRecv   (date)

有人帮我一把吗?

2 个答案:

答案 0 :(得分:0)

您可以使用以下SQL查询(不知道您正在努力解决哪个部分,因此无法提供具体说明):

INSERT INTO tB (tB.ImgRefNum, tB.MTR#, tB.Item, tB.PONum, tB.DateRecv)
SELECT (SELECT Max(tB.ImgRefNum)+1 FROM tB) As NewRef, tA.MTR#, tA.MTRF1, tA.MTRF2, DateSerial(CInt(Mid(tA.MTRF2, 1, 4)),CInt(Mid(tA.MTRF2, 5, 2)), CInt(Mid(tA.MTRF2, 7, 2) ))
FROM tA
WHERE (SELECT Count(s.MTR#) FROM tB AS s WHERE s.MTR# = a.MTR#) = 0

显然,MTRF3始终包含格式正确YYYYMMDD的有效日期字符串至关重要,否则您将遇到错误。

答案 1 :(得分:0)

只需使用熟悉的NOT EXISTS, LEFT JOIN NULL, NOT IN查询即可了解您的日期和最长时间。以下使用NOT EXISTS方法并假设您使用月份优先日期MM/DD/YYYY(基于美国):

INSERT INTO tB ([ImgRefNum], [MTR#], [Item], [PONum], [DateRecv])    
SELECT (SELECT Max(sub.[ImgRefNum]) FROM tA sub) + 1, 
       tA.[MTR#], tA.[MTRF1], tA.[MTRF2], 
       CDate(Mid(tA.[MTRF3], 5, 2) & "/" & Mid(tA.[MTRF3], 7, 2) & "/" &
             LEFT(tA.[MTRF3], 4))
FROM tA
WHERE NOT EXISTS
  (SELECT 1 FROM tB sub WHERE sub.[MTR#] = tA.[MTR#])