Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create view with with statement

How to create view with a with statement? I'm getting on error on it:

    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

) I'm getting such error :

> Incorrect syntax near the keyword 'CREATE'. 'CREATE VIEW' must be the
> first statement in a query batch.

So, I need just to use Create view using select which based on WITH statement on Sql server 2014

like image 526
mondayguy Avatar asked Feb 05 '23 14:02

mondayguy


1 Answers

Yes always the CREATE has to be the first statement in a query batch

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

Syntax to create a view table using CTE

CREATE VIEW View_Name AS
WITH CTE_Name (Columns) AS (SELECT QUERY)
SELECT QUERY using the CTE Table
GO
like image 55
DataWrangler Avatar answered Feb 07 '23 12:02

DataWrangler