Combining Update & Select SQL statements

前端 未结 1 1973
终归单人心
终归单人心 2021-01-24 10:07

MS Access VBA Scripts that create SQL Statements:

I have a SQL Statement that derives two fields in a new table SATable:

SQLScript = \"SELECT [DATA OUTPU         


        
相关标签:
1条回答
  • 2021-01-24 11:02

    Okay, so I might be making an assumption or two, but it looks like what you really want to do is to join [DATA OUTPUT TABLE] (@tDataOutputTable in my script) on itself (similar to what you're doing) and only update records that match on JVIDs, but not dBranch

    Now, this will match any record where the dBranch columns don't match. If you only want this to happen for dBranch of 'Navy' and 'USMC', then you'll want to replace my d.dBranch <> d2.dBranch with something more like what you have.

    Here is a SQL script that I created to test it:

    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
    

    I'm not that familiar with the intricacies of VBA and Access, but hopefully something like this should work:

    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
    
    0 讨论(0)
提交回复
热议问题