WITH AS (SELECT) 语句的 CREATE VIEW 语法
Posted
技术标签:
【中文标题】WITH AS (SELECT) 语句的 CREATE VIEW 语法【英文标题】:CREATE VIEW syntax for WITH AS (SELECT) statements 【发布时间】:2018-07-11 20:10:17 【问题描述】:SQL Server:我有以下工作 SQL 语句:
WITH required_skills AS
(
SELECT DISTINCT
e.empl_ID, e.job_code, j.skill_ID, j.skill_desc
FROM
emplskills e
JOIN
jobskills j ON e.job_code = j.job_code
)
SELECT
r.empl_ID, e.emplName, r.job_code, r.skill_ID, r.skill_desc
FROM
required_skills r
FULL OUTER JOIN
emplskills e ON r.empl_ID = e.empl_ID
AND r.skill_ID = e.skill_ID;
我想将此语句的输出转换为视图。我以为我可以这样做:
CREATE VIEW MY_VIEW
AS
(WITH required_skills AS
(
SELECT DISTINCT
e.empl_ID, e.job_code, j.skill_ID, j.skill_desc
FROM
emplskills e
JOIN
jobskills j ON e.job_code = j.job_code
)
SELECT
r.empl_ID, e.emplName, r.job_code, r.skill_ID, r.skill_desc
FROM
required_skills r
FULL OUTER JOIN
emplskills e ON r.empl_ID = e.empl_ID AND r.skill_ID = e.skill_ID
);
但它出错了:
“WITH”附近的语法不正确
有人可以帮忙吗?
TIA, 约翰
【问题讨论】:
【参考方案1】:去掉AS后面的括号
CREATE VIEW MyViewName
AS
WITH required_skills as (
SELECT DISTINCT e.empl_ID, e.job_code, j.skill_ID, j.skill_desc
FROM emplskills e
JOIN jobskills j
ON e.job_code = j.job_code
)
SELECT r.empl_ID, e.emplName, r.job_code, r.skill_ID, r.skill_desc
FROM required_skills r
FULL OUTER JOIN emplskills e
ON r.empl_ID = e.empl_ID
AND r.skill_ID = e.skill_ID
【讨论】:
宾果游戏。谢谢楼主!WITH
必须是批处理中的第一个语句。我通常会尝试确保我的 CTE 以 ; WITH
开头,只是为了确保。
@Shawn 他们不需要成为批处理中的第一条语句。 SELECT 1; WITH CTE AS (SELECT 1 AS I) SELECT I FROM CTE;
会运行良好。您需要做的是在批处理中用分号 (;
) 终止上一条语句。分号不是“开始”。
SELECT 1
**;
**'WITH CTE...`里面有一个分号,以SELECT 1
结尾,然后WITH CTE
开始。
很高兴它为你工作@JohnJoseph ...一定要标记为答案。以上是关于WITH AS (SELECT) 语句的 CREATE VIEW 语法的主要内容,如果未能解决你的问题,请参考以下文章
请教Sqlserver 2008中使用with as语句递归查询的问题。