我正在尝试使用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();
)Statement
(conn.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;
答案 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