在HSQLDB中,您可以选择变量并在插入中使用它



我正在使用内存中的HSQLDB进行集成测试。

目前我们有各种测试SQL文件,其中包含许多INSERT语句,例如

insert into customer(id, name, email) values (99, 'John Doe', 'john@test.com');
...
insert into order(id, owner, itemref, quantity) values(1, 99,  'abc', 1);
insert into order(id, owner, itemref, quantity) values(2, 99,  'def', 1);
insert into order(id, owner, itemref, quantity) values(3, 99,  'ghi', 1); 

是否可以在变量中进行 SELECT 并随后在 INSERT 中使用它?

例如:

declare custid bigint;
custid = select id from customer where email = 'john@test.com';
insert into order(id, owner, itemref, quantity) values(1, @custid,  'abc', 1);
insert into order(id, owner, itemref, quantity) values(2, @custid,  'def', 1);
insert into order(id, owner, itemref, quantity) values(3, @custid,  'ghi', 1); 

我尝试查看 HSQLDB 文档,但有关"变量"的所有信息都是关于过程的,而不是简单的插入等。

您尝试使用 HSQLDB SqlTool 实现的语法为:

* VARIABLE ~ SQL QUERY RETURNING THE VALUE TO ASSIGN;

然后,您可以将其值进一步用于脚本:

SOME OTHER SQL QUERY WHERE *{VARNAME};

因此,这就是

上面的代码的编写方式:

* custid ~
select id from customer where email = 'john@test.com';
insert into order(id, owner, itemref, quantity) values(1, *{custid},  'abc', 1);
insert into order(id, owner, itemref, quantity) values(2, *{custid},  'def', 1);
insert into order(id, owner, itemref, quantity) values(3, *{custid},  'ghi', 1);

参考:HSQLDB SqlTool - PL 用户变量

你可以这样做:

insert into order(id, owner, itemref, quantity) 
values(1, (select id from customer where email = 'john@test.com'),  'abc', 1);

好吧,如果 INSERT 语句用于测试数据,您可以编写一个简单的 PROCEDURE 包含这些语句。然后,您可以使用此定义一个可更改的会话并调用该过程:

DECLARE myvar VARCHAR(100) DEFAULT 'JOHN@SOMETHING';
CALL myproc(myvar);

会话变量可以是数组,您可以在过程中使用循环插入包含数组元素的多行。

最新更新