关键字 'SCHEMA' 附近的语法不正确。创建时出错

Incorrect syntax near the keyword 'SCHEMA'. ERROR With creating it

我正在尝试创建视图架构,但遇到了一些问题。

你能解释一下吗?我是架构新手。

CREATE VIEW schema.[TEMP1_V](
LOCATION,
OBJECTID,
CTID,
numb,
COUNTALL,
COUNTALL_DEBIT
)
AS SELECT 
LOCATION,
OBJECTID,
CTID,
numb,
COUNTALL,
COUNTALL_DEBIT
COUNT (location) OVER (PARTITION BY location) AS COUNTALL,
COUNT (location) OVER (PARTITION BY location, IS_DEBIT) AS COUNTALL_DEBIT
FROM ALLOCAMT_V

我在尝试创建它时遇到错误。 '关键字 'SCHEMA' 附近的语法不正确。'

我怀疑你的模式实际上叫做 schema。默认值是 dbo 所以这就是我在下面的例子中使用的。您也不需要像以前那样声明您的字段名称。您还在 select 语句中复制了 COUNTALLCOUNTALL_DEBIT 列。

CREATE VIEW dbo.[TEMP1_V]
AS 
SELECT 
    LOCATION,
    OBJECTID,
    CTID,
    numb,
    COUNT (location) OVER (PARTITION BY location) AS COUNTALL,
    COUNT (location) OVER (PARTITION BY location, IS_DEBIT) AS COUNTALL_DEBIT
FROM ALLOCAMT_V

试试 dbo

dbo 是 SQL 服务器中的默认架构。如果您有自己的架构,则可以使用 <schema_name>.[TEMP1_v]

创建此视图
    CREATE VIEW dbo.[TEMP1_V]
    AS SELECT 
    LOCATION,
    OBJECTID,
    CTID,
    numb,
    COUNT (location) OVER (PARTITION BY location) AS COUNTALL,
    COUNT (location) OVER (PARTITION BY location, IS_DEBIT) AS COUNTALL_DEBIT
FROM ALLOCAMT_V

首先,你的例子是这样开始的:

CREATE VIEW

所以,不知道它是如何工作的,我们从 Microsoft 的 MSDN 页面查找 CREATE VIEW - MSDN 并看到以下内容:

CREATE VIEW [ schema_name . ] view_name [ (column [ ,...n ] ) ] 
[ WITH <view_attribute> [ ,...n ] ] 
AS select_statement 
[ WITH CHECK OPTION ] [ ; ]

<view_attribute> ::= 
{
    [ ENCRYPTION ]
    [ SCHEMABINDING ]
    [ VIEW_METADATA ]     }

我们注意到 VIEW 的示例不包括开头部分中的列,因此我们返回到 MSDN 上的定义并查看以下内容:

schema_name

Is the name of the schema to which the view belongs

column

Is the name to be used for a column in a view. A column name is required only when a column is derived from an arithmetic expression, a function, or a constant; when two or more columns may otherwise have the same name, typically because of a join; or when a column in a view is specified a name different from that of the column from which it is derived. Column names can also be assigned in the SELECT statement.

If column is not specified, the view columns acquire the same names as the columns in the SELECT statement.

更新:因此没有理由在这里定义列,因为您的查询已经这样做了。

这给我们带来了这些结论:

  • 语法问题使用MSDN
  • 仅在绝对必要时才指定视图中的列。
  • 只能在当前database
  • 中创建视图