我使用 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 的轻微修改:我删除了空行并将多行查询转换为单行查询。
但我想了解我的根本原因。请帮助我!
提前致谢!