这个SQL Server查询有什么问题

时间:2018-04-13 10:55:41

标签: sql sql-server

以下更新查询有什么问题?它给出了语法错误,错误信息如下:

  

Msg 102,Level 15,State 1,Line 1
  'a'附近的语法不正确。

代码:

UPDATE D_date a 
SET d_date_key = b.d_date_key,  
    full_date = b.full_date,    
    day_of_week = b.day_of_week,    
    day_of_week_display = b.day_of_week_display,    
    fiscal_day_number = b.fiscal_day_number 
FROM   
    dbo.[2017 Calendar update] b
WHERE  
    a.d_date_key = b.d_date_key;

2 个答案:

答案 0 :(得分:6)

您没有在UPDATE子句中为要更新的表添加别名,而是FROM中的别名。正确的语法是:

UPDATE a
SET d_date_key =b.d_date_key ,  
    full_date=b.full_date,  
    day_of_week=b.day_of_week,  
    day_of_week_display=b.day_of_week_display,  
    fiscal_day_number=b.fiscal_day_number   
FROM D_date a
     JOIN dbo.[2017 Calendar update] b ON a.d_date_key = b.d_date_key;
然而,使用升序字母字符(abcd)或类似想法(如{{1} }},T1T2等等,因为它们对每个人都毫无意义。使用适当的别名。例如T3的{​​{1}}和D的{​​{1}}。

答案 1 :(得分:1)

显然,SQL Server中update语句的update部分不允许使用别名。而只需使用表名:

UPDATE D_date 
    SET d_date_key = b.d_date_key ,  
        full_date = b.full_date,  
        day_of_week = b.day_of_week,  
        day_of_week_display = b.day_of_week_display,  
        fiscal_day_number = b.fiscal_day_number   
    FROM  dbo.[2017 Calendar update] b
    WHERE D_date.d_date_key = b.d_date_key;

或者使用明确的JOIN和合理的别名:

UPDATE D_date 
    SET d_date_key = cu.d_date_key ,  
        full_date = cu.full_date,  
        day_of_week = cu.day_of_week,  
        day_of_week_display = cu.day_of_week_display,  
        fiscal_day_number = cu.fiscal_day_number   
    FROM D_date d JOIN
         dbo.[2017 Calendar update] cu
         ON d.d_date_key = cu.d_date_key;