SQL statement - creating a view

I am trying to create a SQL view and keep getting the error message: Msg 111, Level 15, State 1, Line 8
'CREATE VIEW' must be the first statement in a query batch.

Here is the SQL statement.  It runs fine without the "create view" statement

-- Open transactions

declare @segnumstr varchar(3)
declare @statement varchar(3333)

select @segnumstr=SGMTNUMB from SY00300 where SGMTNAME in (select BSSI_Facility_Segment from B3900100)
select @statement=
'from GL20000 G ' +
'inner join B3940200 B on G.JRNENTRY=B.JRNENTRY and G.OPENYEAR=B.OPENYEAR ' +
'inner join GL00100 A on A.ACTINDX=G.ACTINDX ' +
'where A.ACCTTYPE=1 ' +
'group by G.OPENYEAR, G.JRNENTRY, G.TRXDATE, A.ACTNUMBR_' + @segnumstr + ' ' +
'order by TRXDATE '
exec (@statement)
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Aneesh RetnakaranDatabase AdministratorCommented:
A view supports only SELECT statements, you cant have DECLARE or EXEC statement in a view.
You probably should consider a stored procedure

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
pstreAuthor Commented:
How do I create a stored procedure?
Athar SyedCommented:
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.