1

我使用 SQL Server Management Studio 中的以下 SQL 脚本在 SQL Server DB 中创建视图:

use DB_1
go

if exists (select * from sysobjects where name='view_name' and xtype='V')
    drop view view_name
go

create view view_name as (
select l.* from table_name l join (select col_1, col_2 from table_name group by   col_2, col_1 having col_1=max(col_1)) m on (l.col_2=m.col_2and l.col_1 = m.col_1) 
)
go

use DB_2
go

if exists (select * from sysobjects where name='view_name' and xtype='V')
    drop view view_name
go

create view view_name as (
select l.* from table_name l join (select col_1, col_2 from table_name group by col_2, col_1 having col_1=max(col_1)) m on (l.col_2=m.col_2 and l.col_1 = m.col_1) 
)
go

if exists (select * from sysobjects where name='view_name_2' and xtype='V')
drop view view_name_2
go


create view view_name_2 as (
select l.* from table_name_2 l join (select col_1, col_2 from table_name_2 group by col_2, col_1 having col_1=max(col_1)) m on (l.col_2=m.col_2 and l.col_1 = m.col_1) 
)
go

我有一些 Groovy 脚本来执行其他 SQL 脚本,所以我只是尝试与其他脚本完全类比来执行这个:

Sql.withInstance( ...connection_params... ){
    it.execute( ( new File( 'Script.sql' ) ).text )
}

其中 Script.sql 是上面提到的带有少量修改的 SQL 查询(没有 'GO' 语句)。

我在执行期间收到此 Groovy 脚本的以下错误:

... create view should be the first in query batch ...

我不明白这个错误。我应该在脚本中更正什么来执行这个?

我尝试创建一些解决方法并让以下解决方法为我工作:

Sql.withInstance( ...connection_params... ){ oSQL ->
        ( new File( 'Script_2.sql' ) ).eachLine{ oSQL.execute( it ) }
    }

其中 Script_2.sql 是对 Script.sql 的轻微修改:我删除了空行并将多行查询转换为单行查询。

但我想了解我的根本原因。请帮助我!

提前致谢!

4

1 回答 1

0

我对 Groovy 一无所知。但是,SQL 中的某些命令应该首先出现。其中之一是“创建视图”。“GO”是批次分隔符。因此,如果您同时处理多个 SQL 语句,其中一个是“创建视图”,它必须是第一个 - 或者通过“go”与批处理分开。您可能会发现这是任意的,但是这背后有充分的理由。在大多数情况下,它通常会锁定对象和资源。这是一个讨论https://dba.stackexchange.com/questions/34654/sql-server-must-be-first-statement-in-query-batch-what-and-why原因可能与 SQL 如何处理各种对象以及需要保持事务之间的一致性等有关。使用 MS SQL 可以获得许多非常好的东西,但也有一些限制,这就是其中之一。只需要解决它。

于 2013-06-25T17:04:27.640 回答