SQL Query Declaration problem
You cannot use declare and any code manipulation in view (select statement ONLY at SQL Server of course). 

CREATE VIEW [ schema_name . ] view_name [ (column [ ,...n ] ) ] 
[ WITH &lt;view_attribute&gt; [ ,...n ] ] 
AS select_statement 
[ WITH CHECK OPTION ] [ ; ]

&lt;view_attribute&gt; ::= 
{
    [ ENCRYPTION ]
    [ SCHEMABINDING ]
    [ VIEW_METADATA ]     } 


See for more details

Use stored procedure instead of view