使用可选参数运行SQL查询的最佳方法是什么?

时间:2021-04-09 17:02:00

I'm currently running the following query to add data to a table in my database:

我目前正在运行以下查询以将数据添加到我的数据库中的表:

INSERT INTO IDEIAS_INTERACOES (CODIGO, ARQUIVO, REMETENTE, MENSAGEM, UNIT, DATA) 
VALUES (@codigo, @file, @remetente, @mensagem, @unit, @data)

This works fine, however the @file argument isn't always present, and I want the column to be 'Undefined' in that case. I can accomplish this easily using ternary operators, but the resultant code is messy and probably unoptimal. What's a more elegant way of accomplishing this?

这样可以正常工作,但是@file参数并不总是存在,我希望在这种情况下该列为“Undefined”。我可以使用三元运算符轻松完成此任务,但结果代码很混乱,可能不是最理想的。什么是更优雅的方式来实现这一目标?

Ps.: I'm using the mssql module.

Ps。:我正在使用mssql模块。

1 个解决方案

#1


3  

Based on your comments, when the @file is not present, its value is 'undefined'. You can use NULLIF to look for that value and return a NULL:

根据您的注释,当@file不存在时,其值为'undefined'。您可以使用NULLIF查找该值并返回NULL:

INSERT INTO IDEIAS_INTERACOES (CODIGO, ARQUIVO, REMETENTE, MENSAGEM, UNIT, DATA) 
VALUES (@codigo, NULLIF(@file, 'Undefined'), @remetente, @mensagem, @unit, @data)

#1


3  

Based on your comments, when the @file is not present, its value is 'undefined'. You can use NULLIF to look for that value and return a NULL:

根据您的注释,当@file不存在时,其值为'undefined'。您可以使用NULLIF查找该值并返回NULL:

INSERT INTO IDEIAS_INTERACOES (CODIGO, ARQUIVO, REMETENTE, MENSAGEM, UNIT, DATA) 
VALUES (@codigo, NULLIF(@file, 'Undefined'), @remetente, @mensagem, @unit, @data)