Creating a View using stored procedure

狂风中的少年 提交于 2019-11-29 16:06:02

If you want to create a view from within a SP you need to use dynamic SQL.

Something like this.

create procedure ProcToCreateView 
as
exec ('create view MyView as select 1 as Col')

The create view... code has to be sent as a string parameter to exec and by the looks of it you already have the code you need for the view so just embed it in between the '.

I really have no idea why you need that. Perhaps you just need to know how to use a view from a SP

create procedure ProcToUseView
as
select Col
from MyView

I use the following dynamic SQL code in my SQL database to create a view with a store procedure. It works fine:

    CREATE PROCEDURE uspCreateView
    AS
    EXEC ('

    CREATE VIEW vwDataLayoutFileAssignment
    AS

    SELECT b.FileID, d.FieldID
    FROM [File] b, DataLayoutFileAssignment c, [Field] d
    WHERE b.DriverFileID = c.FileID
    AND C.DataLayoutID = d.DataLayoutID
    ')

Using Joins from MS BOL

And from a close page

Outer join conditions, however, may interact differently with the WHERE clause search conditions, depending on whether the join conditions are in the FROM or WHERE clause. Therefore, the ability to specify Transact-SQL outer joins in the WHERE clause is not recommended, is no longer documented, and will be dropped in a future release.

So that turns your code into:

CREATE VIEW ExpenseView AS
BEGIN
   SELECT [Employee Expense].[Employee ID], Employee.[First Name], [Employee Expense].[Expense Type],[Employee Expense].[Expense Amount],[Employee Expense].[Expense Date]
   FROM Employee
   LEFT OUTER JOIN [Employee Expense]
   ON [Employee Expense].[Employee ID] = Employee.[Employee ID]
END
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!