sqlite 如何在一个SQL语句中插入一个可选列?

r3i60tvu  于 2023-05-23  发布在  SQLite
关注(0)|答案(1)|浏览(178)

假设我有一个DB表:

Account (userId TEXT, password TEXT).

我想向表中插入一条带有可选密码记录,如下所示:

var userId = 'user1';
var password = getPassword(); // may reurn empty string

if (password NOT empty)
    INSERT INTO Account(userId, password) VALUES(userId, password);
else
    INSERT INTO Account(userId) VALUES(userId);

我可以用一个语句处理上述两个语句吗?

bpsygsoo

bpsygsoo1#

假设你在一个预处理语句中使用命名参数,你可以这样做:

INSERT INTO Account(userId, password) VALUES (:userId, NULLIF(:password, ''));

或:

INSERT INTO Account(userId, password) SELECT :userId, NULLIF(:password, '');

如果:password是一个空字符串(如果没有提供密码,这就是你想要的),函数NULLIF()将返回NULL,或者在任何其他情况下返回:password

相关问题