SQL SERVER

SQL Server Guide: Create a View Based on a Stored Procedure

intro

Let's find out how to create a view based on a stored procedure in SQL Server to avoid setting up views at runtime.

Tools used in the tutorial
Tool Description Link
Dbvisualizer DBVISUALIZER
TOP RATED DATABASE MANAGEMENT TOOL AND SQL CLIENT

"SQL Server create view based on stored procedure" is a highly searched phrase in the database field. Why is this issue so popular? Let's discover it in this article!

In this blog, you will learn whether it is possible to create views within stored procedures and how to do so in SQL Server.

Let's dive in!

Is It Possible to Create a View Using a Stored Procedure in SQL Server?

Yes, that is possible with some dynamic SQL logic. If you are not familiar with it, dynamic SQL allows you to execute SQL statements that are generated and run at runtime.

In detail, you can create a view using a stored procedure in SQL Server as below:

Copy
        
1 CREATE PROCEDURE StoredProcedureName 2 AS 3 BEGIN 4 EXEC( 5 -- CREATE VIEW... 6 ); 7 END;

The idea is to execute a CREATE VIEW statement within the procedure using the EXEC—or equivalent EXECUTE—command. EXEC will dynamically run the query you passed as a string at runtime, creating the view as desired, while EXECUTE acts as its symlink.

For further reading, check out our guide on how to efficiently create and manage views in SQL.

Why Create Views With Stored Procedures

While creating views with a stored procedure is not a standard scenario, it brings three significant benefits:

  • Improved testing: During development or testing, you may need to create and drop views multiple times. Using a stored procedure simplifies this process as you can automate the creation of views and reset your environment quickly.
  • Reusability: By encapsulating the CREATE VIEW logic in a stored procedure, you can easily create a view with a single EXEC command.
  • Parameterization: Stored procedures can accept parameters, enabling you to create customized views based on input values. That adds flexibility, allowing you to tailor views without manually editing SQL statements each time.

How to Create a View Based on a Stored Procedure in SQL Server

In this guided section, you will see how to create a view within a stored procedure in SQL Server.

The steps will be executed in DbVisualizer, a top-ranked database client that fully supports SQL Server and dozens of other databases. Note that executing queries from the CLI or using any other database client will also work.

Follow the steps below and create a view based on a stored procedure!

Step 1: Connect To Your SQL Server Database

Use the CLI or a database client to connect to the SQL Server database you want to operate on. In this example, the database is called "Company":

Visually selecting a database in DbVisualizer
Visually selecting a database in DbVisualizer

Step 2: Create the Stored Procedure to Define a View

Assume that your goal is to define a stored procedure that creates a view for retrieving all employees who work in the "Marketing" department. As mentioned earlier, you can accomplish that by using the dynamic SQL EXEC (or EXECUTE) statement within the stored procedure definition.

When you execute the query below, it will create a stored procedure called CreatemarketersView. This procedure, when called, will launch the CREATE VIEW statement to generate the Marketers view:

Copy
        
1 CREATE PROCEDURE CreateMarketersView 2 AS 3 BEGIN 4 EXEC('CREATE VIEW Marketers AS 5 SELECT * 6 FROM Employees 7 WHERE Department = ''Marketing'''); 8 END;

If you are a DbVisulizer user, you can visually make sure that the stored procedure to create a view was added by expanding the "Stored Procedure" dropdown as below:

Note the newly created CreateMarktersView stored procedure
Note the newly created CreateMarktersView stored procedure

Great, as you can see, the CreateMarketersView procedure has been added as expected!

The CreateMarketersView procedure creates the Marketers view, so calling it more than one time leads to the following error:

Copy
        
1 [Code: 2714, SQL State: S0001] There is already an object named 'Marketers' in the database.

To avoid that, you can use the OR ALTER clause from SQL Server 2016 SP1 as below:

Copy
        
1 CREATE PROCEDURE CreateMarketersView 2 AS 3 BEGIN 4 EXEC('CREATE VIEW OR ALTER Marketers AS 5 SELECT * 6 FROM Employees 7 WHERE Department = ''Marketing'''); 8 END;

This will instruct SQL Server to conditionally alter the view if it already exists, avoiding the error.

Note that DbVisualizer also allows you to visually create SQL stored procedures.

Step 3: Execute the Stored Procedure

Launch the stored procedure in SQL Server with the EXEC command:

Copy
        
1 EXEC CreateMarketersView;

Equivalently, if you are a DbVisualizer user, you can right-click on the "CreateMarketersView" procedure, click "Open in New Tab" and press the "Execute" button:

Executing a stored procedure in DbVisualizer
Executing a stored procedure in DbVisualizer

Now, a Marketers view will appear in your database:

Note the newly created Marketer view
Note the newly created Marketer view

Amazing! The Marketers view has been created as desired.

Step 4: Query the View

You can query the Marketers view with the following SELECT statement:

Copy
        
1 SELECT * FROM Marketers;

The result will look something like this:

Querying the Marketers view in DbVisualizer
Querying the Marketers view in DbVisualizer

Et voilà! You just SQL Server to create a view based on a stored procedure.

Conclusion

In this article, you learned how and why to create a view within a stored procedure in SQL Server. As discussed, that is possible thanks to the EXEC dynamic SQL command. Working with views and stored procedures becomes much easier with a visual database client like DbVisualizer.

DbVisualizer supports numerous DBMSs and offers in-line data editing, advanced query optimization, and drag-and-drop query construction. Download DbVisualizer for free now!

FAQ

How to create a view within a stored procedure in SQL Server?

You can create a view inside a stored procedure in SQL Server by calling CREATE VIEW inside EXEC, as in the following example:

Copy
        
1 CREATE PROCEDURE StoredProcedureName 2 AS 3 BEGIN 4 EXEC( 5 CREATE VIEW MyView as 6 SELECT 1 AS MyColumn 7 ); 8 END;

Why do so many people look for the "sql server create view based on stored procedure" keyphrase?

Many people search online for the keyphrase "SQL Server create view based on stored procedure" because creating views inside stored procedures offers the benefits of reusability and parameterization, which are typical advantages of stored procedures.

How to call a stored procedure inside a view in SQL Server?

You cannot run stored procedures from a view, as stored procedures require the EXEC command for dynamic SQL execution. However, a view is nothing more than a static, predefined query, without any dynamic capabilities. For more details, refer to the dedicated discussion on the official Microsoft SQL Server forum.

How to use a view in a stored procedure in SQL Server?

You can use a view in a stored procedure in SQL Server you just like any other table. Make sure your database contains the desired view and then SELECT within the stored procedure just like a regular table:

Copy
        
1 CREATE PROCEDURE MyStoredProcedure 2 AS 3 BEGIN 4 SELECT * FROM MyView; 5 END;

How does DbVisualizer make it easier to deal with stored procedures and views?

DbVisualizer, a top-rated database client, simplifies working with views and stored procedures by providing an intuitive and user-friendly interface. It allows users to create, delete, update, and inspect views and stored procedures visually. Explore all DbVisualizer's features!

Dbvis download link img
About the author
Antonello Zanini

Antonello is a software engineer, and often refers to himself as a technology bishop. His mission is to spread knowledge through writing.

The Table Icon
Sign up to receive The Table's roundup
More from the table
Title Author Tags Length Published
title

A Guide To the SQL DECLARE Statement

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SERVER 7 min 2024-12-12
title

SQL Upsert: Inserting a Record If It Does Not Exist

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2024-12-10
title

How and Why to Add an Index in SQL

author Lukas Vileikis tags MySQL POSTGRESQL Search SQL SQL SERVER 8 min 2024-11-28
title

List of SQL Reserved Words in All Major Databases

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 16 min 2024-11-20
title

SQL Variable: What It Is and How To Use It

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2024-11-18
title

SQL Server CTE: Everything You Need to Know

author Antonello Zanini tags SQL SERVER 9 min 2024-11-14
title

The Definitive Guide to the SQL Server GETDATE Function

author Antonello Zanini tags SQL SERVER 6 min 2024-10-31
title

CONCAT_WS SQL Server Function: Ultimate Guide With Examples

author Antonello Zanini tags SQL SERVER 6 min 2024-10-24
title

The Ultimate Guide to the SQL Server Date Format

author Antonello Zanini tags DATE SQL SERVER 9 min 2024-10-23
title

SQL Not Equal Operator: Definitive Guide with Examples

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 6 min 2024-10-14

The content provided on dbvis.com/thetable, including but not limited to code and examples, is intended for educational and informational purposes only. We do not make any warranties or representations of any kind. Read more here.

Cookie policy

We use cookies to ensure that we give you the best experience on our website. However you can change your cookie settings at any time in your browser settings. Please find our cookie policy here ↗