简体   繁体   中英

What is the most optimal way of running an SQL Query with optional arguments?

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?

Ps.: I'm using the mssql module.

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM