使用 with 语句创建视图

mon*_*guy 4 sql sql-server view with-statement

如何使用 with 语句创建视图?我遇到了错误:

    WITH temp as (
select uu.email, u.logintime, u.region, p.id as panelid, p.panelname, p.numberofdownloads, dimensionType + ' (' + dimensionValue + ')' as filter
from stat_users u
left join stat_panels p
on u.id=p.sessionid
left join stat_filters f
on p.id=f.panelid
left join users uu
on uu.id=u.userid
where uu.Organization = 'name' AND
     year(logintime) between 2015 and 2017
    and panelname is not  null
)


CREATE VIEW final as(
    select aa.email, aa.logintime, aa.region, aa.panelname, aa.numberofdownloads as downloads, case when len(aa.filters) > 0 then left(aa.filters, len(aa.filters)-1) else '' end as filters
    from (
    Select distinct a.email, a.logintime, a.region, a.panelname, a.numberofdownloads,
                (
                    Select b.filter + ', ' AS [text()]
                    From temp b
                    Where b.panelid=a.panelid
                    ORDER BY b.panelid
                    For XML PATH ('')
                ) filters
    from temp a
    ) aa
Run Code Online (Sandbox Code Playgroud)

) 我收到这样的错误:

> Incorrect syntax near the keyword 'CREATE'. 'CREATE VIEW' must be the
> first statement in a query batch.
Run Code Online (Sandbox Code Playgroud)

所以,我只需要使用基于 Sql server 2014 上的 WITH 语句的 select 来创建视图

小智 5

是的CREATE,必须是查询批处理中的第一条语句

CREATE VIEW vFinal AS 
WITH Temp AS (
SELECT uu.email, u.logintime, u.region, p.id AS panelid, p.panelname, p.numberofdownloads, dimensionType + ' (' + dimensionValue + ')' AS Filter
FROM stat_users u
LEFT JOIN stat_panels p ON u.id=p.sessionid
LEFT JOIN stat_filters f ON p.id=f.panelid
LEFT JOIN users uu ON uu.id=u.userid
WHERE uu.Organization = 'name' AND
                        YEAR(logintime) BETWEEN 2015 AND 2017
                        AND panelname IS NOT  NULL
)
SELECT aa.email, aa.logintime, aa.region, aa.panelname, aa.numberofdownloads AS downloads, CASE WHEN LEN(aa.filters) > 0 THEN LEFT(aa.filters, LEN(aa.filters)-1) else '' end as filters
    FROM (
    SELECT DISTINCT a.email, a.logintime, a.region, a.panelname, a.numberofdownloads,
                (
                    SELECT b.filter + ', ' AS [text()]
                    FROM temp b
                    WHERE b.panelid=a.panelid
                    ORDER BY b.panelid
                    FOR XML PATH ('')
                ) filters
    FROM temp a
    ) aa

GO
Run Code Online (Sandbox Code Playgroud)

使用创建视图表的语法 CTE

CREATE VIEW View_Name AS
WITH CTE_Name (Columns) AS (SELECT QUERY)
SELECT QUERY using the CTE Table
GO
Run Code Online (Sandbox Code Playgroud)