SQLScript 现在支持将 SELECT 作为标量表达式中的 SQL 查询。
如果 SELECT 语句返回 1*1 结果集(1 行和 1 列),则该结果集可直接用作表达式。
可能存在以下用例:
示例代码x = (SELECT TOP 1 val from mytab) * 10; ... IF (SELECT MAX(val) FROM mytab) > 100 THEN ... 子查询的结果集大小应为 1*1,但如果结果集有 0 条记录,则返回空值。在任何其他情况下,您将收到错误消息。
create table multiple_col_tab(i int, j int);
insert into multiple_col_tab values(1, 2);
do begin
declare n int = (select * from multiple_col_tab) + 1; -- ERR-00269: too many values
end;
create table multiple_row_tab(i int);
insert into multiple_row_tab values(1);
insert into multiple_row_tab values(2);
do begin
declare n int = (select * from multiple_row_tab) + 1; -- ERR-01300: fetch returns more than requested number of rows
end;
create table empty_tab(i int);
do begin
declare n int = (select * from empty_tab) + 1; -- n has null value
end;
如果赋值的右侧仅包含 SELECT 语句(即使带括号,例如: x = (SELECT * FROM tab) ),则始终将其视为表变量分配。解决方法是使用 SELECT INTO。
create table mytab(i int);
insert into mytab values(1);
do begin
declare n int;
n = (select i from mytab); -- ERR-01310: scalar type is not allowed: N
end;
do begin
declare n int;
select i into n from mytab; -- workaround
end;
不支持自动类型 。
do begin
declare n auto = (select 10 from dummy) + 1; -- ERR-00007: feature not supported: subquery in auto type assignment
end;