在SQL中以相​​同的批处理创建多个视图

时间:2017-12-14 17:35:50

标签: sql tsql view create-view

我尝试运行一个脚本,为特定数据库的每个表创建一个视图。 我找到了这个链接: How to create view for all tables in database?

显然,为了工作,我需要添加“GO'声明和回车。所以这就是我做的事情

DECLARE @SQL NVARCHAR(MAX)
SET @SQL = ''

SELECT
    @SQL = @SQL+
    N'CREATE VIEW [v2_' + t.name + N'] AS SELECT ' + 
        STUFF(
            (SELECT N',' + c.name
               FROM
                  sys.columns AS c
               WHERE 
                 c.OBJECT_ID = t.OBJECT_ID
               ORDER BY
                 column_id
               FOR XML PATH(''), TYPE).value('.',N'nvarchar(max)')
        ,1,1,N'')
        + N' FROM [' + t.name + N'] [\r\n]go[\r\n]'

FROM
    sys.tables AS t
WHERE
    t.schema_id ='1'

SET @SQL = REPLACE(@SQL,'[\r\n]',CHAR(13)+CHAR(10))
PRINT @SQL

EXECUTE (@SQL)

因此打印结果符合我的预期:

CREATE VIEW ***** AS SELECT Parent_Path,id,a2ea,userLabel,DATE,HEURE,REF_EQT,COMMANDE_REF,LOG FROM ***** 
go
CREATE VIEW ***** AS SELECT AlarmIdentifier,Class,Category,Time,ObjectOfReference,AlarmText,DATE,HEURE,REF_EQT,SS_EQT,Carte_EQT,COMMANDE_REF,LOG FROM ***** 
go
CREATE VIEW ***** AS SELECT CELL,MCC,MNC,LAC,CID,BSC,CO,EA,RO,NCS,DATE,HEURE,REF_EQT,SS_EQT,Carte_EQT,COMMANDE_REF,LOG FROM ***** 
go
CREATE VIEW ***** AS SELECT RNC,RNCID,R1,R2,GLCNID,RNCCODEC,TB,DATE,HEURE,REF_EQT,SS_EQT,Carte_EQT,COMMANDE_REF,LOG FROM ***** 
go
CREATE VIEW ***** AS SELECT MGG,MG,RESTRICTED,DEFAULT,MISC,MGP,WF,DATE,HEURE,REF_EQT,SS_EQT,Carte_EQT,COMMANDE_REF,LOG FROM [NRGGP] 
go
CREATE VIEW ***** AS SELECT SNT,SNTV,SNTP,DIP,DEV,DEVP,SNTINL,EQLEV,PROT,SDIP,SUBSNT,DEFPST,EXTP,MG,DATE,HEURE,REF_EQT,COMMANDE_REF,LOG FROM *****
go
CREATE VIEW ***** AS SELECT RefreshLog_Id,Date,Etat,DateTransfert,Transfert FROM ***** 
go

但是exec行返回:

  

Msg 156,Level 15,State 1,Procedure *****,Line 3 [Batch Start Line 0]
  关键字' CREATE'。

附近的语法不正确      

Msg 111,Level 15,State 1,Procedure *****,Line 3 [Batch Start Line 0]
  '创建视图'必须是查询批处理中的第一个语句。

     

Msg 111,Level 15,State 1,Procedure *****,Line 5 [Batch Start Line 0]
  '创建视图'必须是查询批处理中的第一个语句。

     

Msg 111,Level 15,State 1,Procedure *****,Line 7 [Batch Start Line 0]

我应该创建架构吗?我问题的任何解决方案?

非常感谢

3 个答案:

答案 0 :(得分:0)

使用光标并执行 sp_executesql 似乎可以正常工作

DECLARE @SQL NVARCHAR(MAX)
       , @table_id INT
SET @SQL = ''

DECLARE CUR CURSOR LOCAL FAST_FORWARD FOR
SELECT t.object_id FROM sys.tables AS t
WHERE t.schema_id ='1'

OPEN CUR

FETCH NEXT FROM cur INTO @table_id
WHILE @@FETCH_STATUS = 0
BEGIN

    SELECT @SQL = N'CREATE VIEW [v2_' + t.name + N'] AS SELECT ' + 
            STUFF(
                (SELECT N',' + c.name
                   FROM
                      sys.columns AS c
                   WHERE 
                     c.OBJECT_ID = t.OBJECT_ID
                   ORDER BY
                     column_id
                   FOR XML PATH(''), TYPE).value('.',N'nvarchar(max)')
            ,1,1,N'')
            + N' FROM [' + t.name + N'];'
    FROM
        sys.tables AS t
    WHERE t.object_id = @table_id 

    PRINT @SQL
    --EXECUTE sp_executesql @SQL
    FETCH NEXT FROM cur INTO @table_id
END

CLOSE CUR

DEALLOCATE CUR

答案 1 :(得分:0)

好的,最后我做了你们建议的,我创建了一个光标,它可以工作。谢谢。

DECLARE @TableName as NVARCHAR(50)
DECLARE @TableCursor as CURSOR

SET @TableCursor = CURSOR FOR
SELECT TABLE_NAME 
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_TYPE='BASE TABLE' and TABLE_SCHEMA = 'dbo';

OPEN @TableCursor;

FETCH NEXT FROM @TableCursor INTO @TableName;

While @@FETCH_STATUS = 0

BEGIN
    EXEC ('create view '+ @TableName+'_V2 
    as select * from ' +@TableName +';')
    FETCH NEXT FROM @TableCursor INTO @TableName;
END

CLOSE @TableCursor
DEALLOCATE @TableCursor 

答案 2 :(得分:0)

您应该使用这样的语法:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE VIEW [schema].[viewname] AS
SELECT * FROM schema.table

GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE VIEW [schema].[viewname] AS
SELECT * FROM schema.table

GO

例如:

SELECT 
'SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW ' + TABLE_SCHEMA + '.' + TABLE_NAME + ' AS 
SELECT * FROM ' + TABLE_SCHEMA + '.' + TABLE_NAME + ' 

GO 
'
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'

别忘了以文本格式(在SQL Server Mgmt studio中为CTRL + T)输出结果,因为它将保留回车符。

对于这种情况,您可以生成一个脚本来检查SQL Server如何处理您的脚本。 只需右键单击数据库,“任务”,“生成脚本”并跟随助手。它将完全在SQL Server等待时为您输出文件。