SQL Null 设置为零以进行添加

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/137398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 23:38:15  来源:igfitidea点击:

SQL Null set to Zero for adding

sqlms-accessdatabase-design

提问by Smashery

I have a SQL query (MS Access) and I need to add two columns, either of which may be null. For instance:

我有一个 SQL 查询 (MS Access),我需要添加两列,其中任一列都可能为空。例如:

SELECT Column1, Column2, Column3+Column4 AS [Added Values]
FROM Table

where Column3 or Column4 may be null. In this case, I want null to be considered zero (so 4 + null = 4, null + null = 0).

其中 Column3 或 Column4 可能为空。在这种情况下,我希望 null 被视为零(所以4 + null = 4, null + null = 0)。

Any suggestions as to how to accomplish this?

关于如何实现这一点的任何建议?

回答by Michael Haren

Since ISNULL in Access is a boolean function (one parameter), use it like this:

由于 Access 中的 ISNULL 是一个布尔函数(一个参数),所以像这样使用它:

SELECT Column1, Column2, IIF(ISNULL(Column3),0,Column3) + IIF(ISNULL(Column4),0,Column4) AS [Added Values]
FROM Table

回答by Patrick Honorez

According to Allen Browne, the fastest way is to use IIF(Column3 is Null; 0; Column3)because both NZ()and ISNULL()are VBA functions and calling VBA functions slows down the JET queries.

艾伦·布朗,最快的方法是使用IIF(Column3 is Null; 0; Column3),因为这两个NZ()ISNULL()是VBA函数并调用VBA函数会减慢JET查询。

I would also add that if you work with linked SQL Server or Oracle tables, the IIF syntax also the query to be executed on the server, which is not the case if you use VBA functions.

我还要补充一点,如果您使用链接的 SQL Server 或 Oracle 表,IIF 语法也是要在服务器上执行的查询,如果您使用 VBA 函数,则情况并非如此。

回答by BIBD

Even cleaner would be the nz function

更干净的是 nz 函数

nz (column3, 0)

回答by Ricardo C

The Nz() function from VBA can be used in your MS Access query.

VBA 中的 Nz() 函数可用于 MS Access 查询。

This function substitute a NULL for the value in the given parameter.

此函数用 NULL 替换给定参数中的值。

SELECT Column1, Column2, Nz(Column3, 0) + Nz(Column4, 0) AS [Added Values]
FROM Table

回答by jussij

Use the ISNULLreplacement command:

使用ISNULL替换命令:

 SELECT Column1, Column2, ISNULL(Column3, 0) + ISNULL(Column4, 0) AS [Added Values]FROM Table

回答by Steve C.

In your table definition, set the default for Column3 and Column4 to zero, therefore when a record is added with no value in those columns the column value will be zero. You would therefore never have to worry about null values in queries.

在您的表定义中,将 Column3 和 Column4 的默认值设置为零,因此当在这些列中添加没有值的记录时,列值将为零。因此,您永远不必担心查询中的空值。

回答by Walter Mitty

Use COALESCE.

使用合并。

SELECT 
   Column1, 
   Column2, 
   COALESCE(Column3, 0) + COALESCE(Column4, 0) AS [Added Values]
FROM Table