?
Solved

How to create view??

Posted on 2000-05-07
1
Medium Priority
?
409 Views
Last Modified: 2010-05-18
How can i create a view in a stored procedure?

Here's my sample code:

---------------------------------------
PROCEDURE sp_CreateView (@Model char(3)) AS

declare @ViewName char(6)

select @ViewName = 'vw_' + @Model

create view @ViewName AS
select * from Serial where substring(SerialNo,1,3) = @Model
---------------------------------------
it always prompt me a message 'CREATE VIEW must be the first command in a query batch.'
0
Comment
Question by:yyjulie
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 8

Accepted Solution

by:
chigrik earned 60 total points
ID: 2786909
You can use dynamic SQL statement.
Read about EXEC statement from Books Online.
This is the example:

CREATE PROCEDURE sp_CreateView (@Model char(3)) AS
DECLARE @ViewName char(6),
        @exec_str varchar (255)
SELECT @ViewName = 'vw_' + @Model
SELECT @exec_str = 'CREATE VIEW ' + @ViewName + ' AS
       SELECT * FROM Serial WHERE substring(SerialNo,1,3) = ' + @Model
EXEC (@exec_str)
GO
0

Featured Post

Enterprise Mobility and BYOD For Dummies

Like “For Dummies” books, you can read this in whatever order you choose and learn about mobility and BYOD; and how to put a competitive mobile infrastructure in place. Developed for SMBs and large enterprises alike, you will find helpful use cases, planning, and implementation.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Suggested Courses

801 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question