'Create VIEW' must be the only statement in the batch

时光总嘲笑我的痴心妄想 提交于 2019-12-01 05:21:22

To create a view in a stored procedure, you need to do this in dynamic SQL (especially since the view itself can't take a variable).

DECLARE @sql NVARCHAR(MAX);
SET @sql = 'CREATE VIEW dbo.tblList 
    AS
      SELECT ItemOrder, DisplayVal, 
        SomeAlias = DATEADD(DAY, DaysDue, ''' + CONVERT(CHAR(8), @PDate, 112)
      + ''') FROM dbo.tblLine WHERE ID = 1;';
EXEC sp_executesql @sql;

But once you call this stored procedure a second time, it's going to fail, because you are trying to create a view named dbo.tblList and that view already exists. Perhaps you can elaborate on what you're trying to, at a higher level than "I want to create a view in a stored procedure."

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!