创建SQL语句的MS Access VBA脚本:
我有一个SQL语句,它在新表SATable中派生出两个字段:
SQLScript = "SELECT [DATA OUTPUT TABLE].* INTO SATable"
SQLScript = SQLScript & " FROM [DATA OUTPUT TABLE]"
SQLScript = SQLScript & " WHERE ((([DATA OUTPUT TABLE].[Journal Voucher ID]) In (SELECT [DATA OUTPUT TABLE].[Journal Voucher ID]"
SQLScript = SQLScript & " FROM [DATA OUTPUT TABLE]"
SQLScript = SQLScript & " GROUP BY [DATA OUTPUT TABLE].[Journal Voucher ID]"
SQLScript = SQLScript & " HAVING (((First([DATA OUTPUT TABLE].dBranch))=" & Chr(34) & "Navy" & Chr(34) & ") AND ((Last([DATA OUTPUT TABLE].dBranch))=" & Chr(34) & "USMC" & Chr(34) & ")) OR (((First([DATA OUTPUT TABLE].dBranch))=" & Chr(34) & "USMC" & Chr(34) & ") AND ((Last([DATA OUTPUT TABLE].dBranch))=" & Chr(34) & "Navy" & Chr(34) & "));)));"
DoCmd.RunSQL SQLScript
然后我有一个声明,它接受这两个派生字段并将它们附加到原始表上:
DoCmd.RunSQL "UPDATE SATable INNER JOIN [DATA OUTPUT TABLE] ON (SATable.[Journal Voucher ID] = [DATA OUTPUT TABLE].[Journal Voucher ID]) AND (SATable.dBranch = [DATA OUTPUT TABLE].dBranch) SET [DATA OUTPUT TABLE].[Shared Appropriations] = [SATable].[dBranch] & " & Chr(34) & " Shared Appropriation" & Chr(34) & ";"
我的目标是删除SATable并在一个声明中执行此操作。
我之前一直在努力解决这类问题,而不仅仅是提供一个答案,请你提供一些解释 - 教一个人去钓鱼!
干杯, -E
编辑:--------------------------------------------- ---------------- 数据输出表具有:
JVID dBranch SA
1 Navy N/A
2 Navy N/A
3 Navy N/A
4 Navy N/A
A USMC N/A
B USMC N/A
3 USMC N/A
4 USMC N/A
所以SATable变成了:
JVID dBranch SA
3 Navy Navy SA
3 USMC USMC SA
4 Navy Navy SA
4 USMC USMC SA
然后更新查询更新SA字段,默认为N / A
JVID dBranch SA
1 Navy N/A
2 Navy N/A
3 Navy Navy SA
4 Navy Navy SA
A USMC N/A
B USMC N/A
3 USMC USMC SA
4 USMC USMC SA
答案 0 :(得分:1)
好的,所以我可能会做一两个假设,但看起来你真正想做的就是加入[DATA OUTPUT TABLE]
(@tDataOutputTable
在我的脚本中)自己(类似于你和#39;重做)并且仅更新与JVIDs
匹配的记录,但不更新dBranch
现在,这将匹配dBranch
列不匹配的任何记录。如果你只想让这个发生在海军上面的dBranch上。和USCA&#39;然后你想要用你所拥有的东西替换我的d.dBranch <> d2.dBranch
。
这是我为测试它而创建的SQL脚本:
DECLARE @tDataOutputTable TABLE
(
JVID varchar(max),
dBranch varchar(max),
SA varchar(max)
)
INSERT INTO @tDataOutputTable (JVID, dBranch, SA)
VALUES
('1', 'Navy', 'N/A'),
('2', 'Navy', 'N/A'),
('3', 'Navy', 'N/A'),
('4', 'Navy', 'N/A'),
('A', 'USMC', 'N/A'),
('B', 'USMC', 'N/A'),
('3', 'USMC', 'N/A'),
('4', 'USMC', 'N/A')
UPDATE d
SET d.SA = d.dBranch + ' SA' -- or 'Shared Appropriation'
FROM @tDataOutputTable d
INNER JOIN @tDataOutputTable d2 ON d.JVID = d2.JVID AND d.dBranch <> d2.dBranch
SELECT * FROM @tDataOutputTable
我对VBA和Access的复杂性并不熟悉,但希望这样的事情应该有效:
SQLScript = "UPDATE [DATA OUTPUT TABLE] AS d"
SQLScript = SQLScript & " INNER JOIN [DATA OUTPUT TABLE] AS d2 ON d.JVID = d2.JVID AND d.dBranch <> d2.dBranch"
SQLScript = SQLScript & " SET d.SA = d.dBranch" & Chr(34) & " Shared Appropriation" & Chr(34) & ";"
DoCmd.RunSQL SQLScript