在SQL Server中创建View时出错

时间:2017-10-05 05:33:07

标签: sql sql-server tsql

嗨,任何人都可以帮助我在SQL server toad中创建一个视图时我得到以下错误。感谢高级。

USE [database];
GO
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
CREATE VIEW [dbo].[GCRM_CONTRACT_ENTITLEMENT] ("objid","CONTRACT__TITLE")
AS

(with mycte as (
 SELECT  table1.Column1 as objid, 
 table1.Column2 CONTRACT__TITLE

      FROM table1       
      WHERE
      (
      (table1.struct_type = 0)                
      )     

)

SELECT  Stuff(( SELECT ',' + cast(CONTRACT__TITLE as varchar(2000)) 
           FROM mycte t2
          WHERE t2.[objid] = t1.[objid]             
            FOR XML PATH(''), TYPE).value('.', 'varchar(max)'),1,1,'')  AS [AVILABLE_ENTITLEMENT]
  FROM mycte t1
GROUP BY t1.[objid]
);
GO

错误: - SQL Server数据库错误:关键字附近的语法错误' with'。

1 个答案:

答案 0 :(得分:1)

CTE必须是批次的第一部分,文档是here

将视图的主体更改为以下内容:

WITH mycte(objid,
           CONTRACT__TITLE)
     AS (
     SELECT table1.Column1 AS objid,
            table1.Column2 AS CONTRACT__TITLE
     FROM table1
     WHERE table1.struct_type = 0)
     SELECT STUFF(
                 (
                     SELECT ','+CAST(CONTRACT__TITLE AS VARCHAR(2000))
                     FROM mycte t2
                     WHERE t2.[objid] = t1.[objid] FOR XML PATH(''), TYPE
                 ).value('.', 'varchar(max)'), 1, 1, '') AS [AVILABLE_ENTITLEMENT]
     FROM mycte t1
     GROUP BY t1.[objid];

修改 添加了INCIDENT__ID

WITH mycte(objid,
           CONTRACT__TITLE,
           INCIDENT__ID)
     AS (
     SELECT TABLE1.COLLUMN1 AS objid,
            TABLE1.COLLUMN2 AS CONTRACT__TITLE,
            TABLE2.COLLUMN1 AS INCIDENT__ID
     FROM TABLE1
     WHERE TABLE1.struct_type = 0)
     SELECT STUFF(
                 (
                     SELECT ','+CAST(CONTRACT__TITLE AS VARCHAR(2000))
                     FROM mycte t2
                     WHERE t2.[objid] = t1.[objid] FOR XML PATH(''), TYPE
                 ).value('.', 'varchar(max)'), 1, 1, '') AS [AVILABLE_ENTITLEMENT],
            [INCIDENT__ID]
     FROM mycte t1
     GROUP BY t1.[objid],
              t1.[INCIDENT__ID];