sql server executes stored procedures to create dynamic views

1. Basic view creation method

--查找要创建的视图是否存在--
if exists (select * from sysobjects where name = 'V_QM_RawMaterialMt')
 drop view V_QM_RawMaterialMt
 go
 --创建名称为V_QM_RawMaterialMt的视图--
create view V_QM_RawMaterialMt 
as
 --视图数据来源
   select * from S_Menu
go
--查询视图中的内容--
select * from V_QM_RawMaterialMt

2. Create dynamically based on stored procedures.

ALTER procedure [dbo].[QM_CreateViewRawMaterial]
as
begin
 declare @strSql varchar(max)=''
 set @strSql='
    --创建名称为V_QM_RawMaterialMt的视图--
    create view V_QM_RawMaterialMt 
     as
      '
    set @strSql+=' --**视图数据来源,你可以动态生成你这块的内容**
         select * from S_Menu '
    set @strSql+='
    go'
    --查找要创建的视图是否存在--
    if exists (select * from sysobjects where name = 'V_QM_RawMaterialMt')
      drop view V_QM_RawMaterialMt
      exec(@strSql)
      --查询视图中的内容--
    select * from V_QM_RawMaterialMt
 end 

3. If your view report

**'CREATE VIEW' must be the first statement in the query batch. **This error, then you follow the above method to properly correct your own program, it must be no problem. The results of the operation are as follows
operation result

Guess you like

Origin blog.csdn.net/hello_mr_anan/article/details/103822427