我使用SQL Server 2014上的测试数据库中创建的所有用户数据库视图工作。 从SSMS运行,但在执行命令尝试运行它,我收到以下错误消息时生成的SQL语句工作正常。
SQL查询:
DECLARE @SQL NVARCHAR(MAX),
@QueryStmt NVARCHAR(MAX)
SET @SQL = ''
SELECT @SQL = @SQL + CHAR(13) + 'USE ' + QUOTENAME([name]) + ';
SELECT @QueryStmt = ''USE TestDWH ''+ CHAR(13) + CHAR(10) + ''GO'' + CHAR(13) + CHAR(10) + ''IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(''''TestDWH.'' + s.name + ''.'' + o.name + '''''') AND TYPE IN (''''V'''')) DROP VIEW '' + s.name + ''.'' + o.name + CHAR(13) + CHAR(10) + ''GO'' + CHAR(13) + CHAR(10) + m.[definition] + CHAR(13) + CHAR(10) + ''GO''
FROM sys.objects o JOIN sys.sql_modules m ON m.object_id = o.object_id AND o.[type] = ''V'' JOIN sys.schemas s ON s.schema_id = o.schema_id'
FROM sys.databases
WHERE [database_id] > 4
EXECUTE sp_executesql @SQL, N'@QueryStmt NVARCHAR(MAX) OUT', @QueryStmt OUT
EXECUTE(@QueryStmt)
生成的查询:
USE TestDWH
GO
IF OBJECT_ID('TestDWH.dbo.Test_vw_View1') IS NOT NULL DROP VIEW dbo.Test_vw_View1
GO
CREATE VIEW dbo.Test_vw_View1
AS
SELECT [Id]
,[Description]
FROM [dbo].[Test_Table1]
GO
错误信息:
Msg 102, Level 15, State 1, Line 2 Incorrect syntax near 'GO'. Msg 102, Level 15, State 1, Line 4 Incorrect syntax near 'GO'. Msg 111, Level 15, State 1, Line 5 'CREATE VIEW' must be the first statement in a query batch. Msg 102, Level 15, State 1, Line 84 Incorrect syntax near 'GO'.