返回

PG的空值相加如何实现

发布时间:2022-09-16 08:45:55 307
# php# 数据库# 数据

PostgreSQL数据库中,对于NULL值相加的处理:任何数值和NULL相加都得NULL。

postgres=# create table t3(id1 int,id2 int);
CREATE TABLE
postgres=# insert into t3 select 1,2;
INSERT 0 1
postgres=# insert into t3 select 1,NULL;
INSERT 0 1
postgres=# insert into t3 select NULL,NULL;
INSERT 0 1
postgres=# insert into t3 select NULL,3;
INSERT 0 1
postgres=# select *from t3;
id1 | id2
-----+-----
1 | 2
1 |
|
| 3
(4 行记录)

看下加的结果:

postgres=# select id1+id2 from t3;
?column?
----------
3






(4 行记录)

可以看到只要有一个参数是NULL,那么加的结果就是NULL。那么这个计算是如何实现的呢?

从前文可以了解到操作符“+”的实现机制,真正执行是在ExecInterpExpr函数中:

ExecInterpExpr
EEO_CASE(EEOP_FUNCEXPR_STRICT)//操作符函数的执行
{
FunctionCallInfo fcinfo = op->d.func.fcinfo_data;
NullableDatum *args = fcinfo->args;
int argno;
Datum d;


/* strict function, so check for NULL args */
for (argno = 0; argno < op->d.func.nargs; argno++)
{
if (args[argno].isnull)
{
*op->resnull = true;//只要有一个参数是NULL,就标记resnull为true
goto strictfail;
}
}
fcinfo->isnull = false;
d = op->d.func.fn_addr(fcinfo);
*op->resvalue = d;
*op->resnull = fcinfo->isnull;


strictfail:
EEO_NEXT();
}
...
EEO_CASE(EEOP_ASSIGN_TMP_MAKE_RO)
{
int resultnum = op->d.assign_tmp.resultnum;
//上一步的resnull值传递到resultslot中,标记该slot是一个NULL
resultslot->tts_isnull[resultnum] = state->resnull;
if (!resultslot->tts_isnull[resultnum])
resultslot->tts_values[resultnum] =
MakeExpandedObjectReadOnlyInternal(state->resvalue);
else
resultslot->tts_values[resultnum] = state->resvalue;
EEO_NEXT();
}

这样就完成了NULL值相关的加法计算。

特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像
精选文章
thumb 中国研究员首次曝光美国国安局顶级后门—“方程式组织”
thumb 俄乌线上战争,网络攻击弥漫着数字硝烟
thumb 从网络安全角度了解俄罗斯入侵乌克兰的相关事件时间线
下一篇
#猜数字游戏#函数#22/9/10#三# 2022-09-16 08:18:52