简体   繁体   中英

Can a view be created by a stored procedure?

create procedure pro_training2
as 
begin
    create view Tab1view As
      select * from tab1
end

Is this possible to create a view in the procure?

You can do this using dynamic SQL, eg

CREATE PROCEDURE dbo.pro_training2
AS
BEGIN
  DECLARE @sql NVARCHAR(MAX);

  SET @sql = N'CREATE VIEW dbo.Tab1View AS SELECT <columns> FROM dbo.tab1;';

  EXEC sp_executesql @sql;
END
GO

But this is a serious code smell.

You have tagged with MySQL though the above is not MySQL syntax.

Anyway, if you did mean for MySQL: yes, it is possible to issue CREATE VIEW from within a procedure, but using a different syntax:

CREATE PROCEDURE pro_training2()
MODIFIES SQL DATA

BEGIN
  create view Tab1view As select * from tab1;
END

使用sp_executesql并指定数据库名称:

EXEC myDb1..sp_executesql N'CREATE VIEW Tab1view As select * from tab1'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM