SQLServerException:'CREATE VIEW'必须是查询批处理中的第一个语句

时间:2016-07-25 09:36:53

标签: sql-server jdbc

我正在尝试使用JDBC创建表和两个视图(代码如下所示)。在执行第一个CREATE VIEW查询时,出现以下错误:

com.microsoft.sqlserver.jdbc.SQLServerException: 'CREATE VIEW' must be the first statement in a query batch.

我分别执行每个命令,每个方法抛出该异常。我尝试过的事情:

  • 使用autoCommit(true)
  • 运行 在每个commit 之后
  • execute(sql)
  • 将每个查询作为单个批次(stmt.addBatch(sql); stmt.executeBatch();
  • 运行
  • 使用新的Statementconn.createStatement()
  • 运行每个查询

我可以尝试其他方法吗?

示例代码

CREATE TABLE source (
    a int  NOT NULL,
    b int  NOT NULL,
    c int  NOT NULL,
    d int  NOT NULL,
    CONSTRAINT source_pk PRIMARY KEY  (a)
);

CREATE VIEW "delete"
AS
SELECT a, b FROM source;

CREATE VIEW migrate
AS
SELECT c, d FROM source;

1 个答案:

答案 0 :(得分:3)

尝试在第一个创建视图后添加GO关键字,如

CREATE TABLE source (
    a int  NOT NULL,
    b int  NOT NULL,
    c int  NOT NULL,
    d int  NOT NULL,
    CONSTRAINT source_pk PRIMARY KEY  (a)
);
GO
CREATE VIEW "delete"
AS
SELECT a, b FROM source;
GO

CREATE VIEW migrate
AS
SELECT c, d FROM source;

旁注:尽量避免将您的表命名为关键字。

在JDBC中你可以这样做

if not exists(select 1 from sys.tables where name='SomeDelete')
begin
    exec('CREATE VIEW "SomeDelete" AS SELECT a, b FROM source;');
end
if not exists(select 1 from sys.tables where name='migrate')
begin
    exec('CREATE VIEW migrate AS SELECT c, d FROM source;');
end