尝试在sql server中执行命令时出错

时间:2016-08-31 22:29:56

标签: sql-server tsql sql-server-2014 dynamic-sql

我正在使用SQL Server 2014,并致力于将所有用户数据库中的视图创建到Test数据库。从SSMS运行时生成的sql语句正常工作,但是当execute命令尝试运行它时,我收到以下错误消息。

SQL查询:

'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Users::class,
        ],
        'merchant' => [
            'driver' => 'eloquent',
            'model' => App\Merchant::class,
        ],
    ],

生成的查询:

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

1 个答案:

答案 0 :(得分:2)

在这种情况下,我遵循这个逻辑:

DECLARE @cmdTbl TABLE(id INT IDENTITY,cmd NVARCHAR(MAX));

INSERT INTO @cmdTbl(cmd) VALUES(N'SELECT TOP 3 * FROM INFORMATION_SCHEMA.TABLES');
INSERT INTO @cmdTbl(cmd) VALUES(N'SELECT TOP 3 * FROM INFORMATION_SCHEMA.COLUMNS');

DECLARE @cmd VARCHAR(MAX);
DECLARE cur CURSOR FOR SELECT cmd FROM @cmdTbl ORDER BY id;
OPEN cur;

FETCH NEXT FROM cur INTO @cmd;
WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT @cmd;
    EXEC(@cmd);
    FETCH NEXT FROM cur INTO @cmd;
END
CLOSE cur;
DEALLOCATE cur;

首先是声明的表变量。您可以单独插入所有语句。

GO

您想要设置GO的任何地方只需插入一个新命令。

CURSOR将按您插入的顺序执行所有语句。

在第一次尝试中注释掉EXEC并将所有PRINT - 输出复制到新的查询窗口以检查语法错误。然后一次执行整个批次...