SQL - 关键字附近的语法不正确

时间:2011-11-05 13:38:59

标签: sql syntax

我的查询出现小问题:

CREATE VIEW rental_view
AS 
   SELECT 
       m.movie_id, movie_name, co.copy_id, 
       f.format_id, format_name, cu.customer_id, 
       (first_name + ' ' + surname) AS customer_name, 
       rental_id, rental_date, return_date, 
       ISNULL(return_date, CAST(DATEDIFF(dd, rental_date, GETDATE() ) AS rental_duration 
   FROM 
         movie AS m 
   INNER JOIN copy AS co ON m.movie_id = co.movie_id
   INNER JOIN format AS f ON co.format_id = f.format_id
   INNER JOIN rental ON co.copy_id = rental.copy_id
   INNER JOIN customer AS cu ON rental.customer_id = cu.customer_id

导致错误:

  

Msg 156,Level 15,State 1,
  过程rental_view,第3行关键字'FROM'附近的语法不正确。

我长期尝试这个并且无法解决它。

感谢帮助。

2 个答案:

答案 0 :(得分:5)

你在这一行缺少两个括号:

AS SELECT 
    m.movie_id, movie_name, co.copy_id, f.format_id, format_name, 
    cu.customer_id, (first_name + ' ' + surname) AS customer_name, 
    rental_id, rental_date, return_date, 
    ISNULL(
        return_date, 
        CAST(DATEDIFF(dd, rental_date, GETDATE()))) AS rental_duration 

无论如何,你的语法在其他部分是错误的:

  • CAST希望转换字段,关键字AS和新类型(请参阅docs
  • DATEDIFF想要两个参数(参见docs)< - 如果你正在使用MySql那么这个;使用MS-SQL是正确的

答案 1 :(得分:0)

试试这个:

  CREATE VIEW rental_view
  AS SELECT m.movie_id, 
movie_name, 
co.copy_id, 
f.format_id, 
format_name, 
cu.customer_id, 
(first_name + ' ' + surname) AS customer_name, 
rental_id, 
rental_date, 
return_date,
ISNULL(return_date,
CAST(DATEDIFF(dd, rental_date, GETDATE()) AS *type desired here*)) AS name of column
  FROM movie as m 
  INNER JOIN copy AS co
  ON m.movie_id = co.movie_id
  INNER JOIN format AS f
  ON co.format_id = f.format_id
  INNER JOIN rental 
  ON co.copy_id = rental.copy_id
  INNER JOIN customer AS cu
  ON rental.customer_id = cu.customer_id