Search code examples
c#sqlsql-serverinner-joinsql-server-2014

MS SQL inner join to fill out same column names


Hey all I have 2 tables that have the same data in them. Those tables are called TrainingCity and TrainingState.

I am updating the row in the tEvents table with the users inputted data on the website form. However, tTRIP table attaches to the already entered data on the tEvents table.

I am looking to grab just the TrainingCity and TrainingState values and include them in the update to the tEvents table of the same name columns.

SELECT 
    *, TT.TrainingCity, TT.TrainingState 
FROM 
    tEvents AS TE
INNER JOIN 
    tTRIP AS TT
ON 
    TT.RequestID = TE.RequestID
WHERE 
    TE.EventID = 12
AND 
    TE.RequestID = 801

My update query looks like this:

command = new SqlCommand("UPDATE " +
                            "tEvents " +
                         "SET " +
                             buildTblVal +
                         " WHERE " +
                             "EventID = @eventID " + 
                         "AND " +
                             "RequestID = @reqID", con);

What would the query need to be modified too in order to grab those 2 values from the tTRIP table and place them into the tEvents table?


Solution

  • Well I just got it :)

    UPDATE 
        tEvents 
    SET 
        TrainingState = tT.TrainingState, 
        TrainingCity = tT.TrainingCity,
        ....[other columns here]... 
    FROM (
        SELECT 
            TrainingCity, TrainingState, RequestID  
        FROM 
            tTRIP
         ) AS tT
    WHERE 
        tT.RequestID = tEvents.RequestID
    AND 
        tEvents.EventID = 12
    AND 
        tEvents.RequestID = 801