Search code examples
sqlsql-server-2008sql-updatesubqueryinner-join

Incorrect Syntax - SQL


I am trying to update two fields in my table tbl_prev_data using subquery because I had to use the aggregate SUM. But I don't know why it says

Incorrect Syntax near 't'`

where t is a temp variable that holds the results of the subquery. Am I missing something ? Below is my query.

UPDATE tbl_prev_data
SET Original_Value = t.Original_Value 
SET Pre_Val = t.PreWDV
FROM tbl_prev_data 
INNER JOIN 
    (SELECT 
         Asset_Group_Code, 
         ISNULL(SUM(Original_Value),0) AS 'Original_Value', 
         ISNULL(SUM(Prev_Val),0) AS 'PreWDV' 
     FROM 
         tbl_Asset_Master 
     GROUP BY 
         Asset_Group_Code, DOP 
     HAVING 
         (YEAR(DOP) != YEAR(GETDATE()) AND MONTH (DOP) > 3) t ON tbl_prev_data.Asset_Group_Code = t.Asset_Group_Code

Solution

  • You have to specify SET only once:

    UPDATE tbl_prev_data
        SET Original_Value = t.Original_Value, 
            Pre_Val = t.PreWDV
    FROM tbl_prev_data INNER JOIN ...
    

    Other than that you also need to remove the redundant left parenthesis from the HAVING clause:

    HAVING (YEAR(DOP) != YEAR(GETDATE()) AND MONTH (DOP) > 3
    -------^