Are there different kinds of NULLs?

梦想的初衷 提交于 2020-01-01 13:27:07

问题


This came from

<cfquery name="data">
     SELECT
        NULL                   AS plainNull,
        CAST(NULL AS datetime) AS Due_Date

</cfquery>

Are these two different kinds of nulls? What is the difference

Note: adapted from How can I call a function in another CFC file from within a query of a function in one cfc file?


回答1:


Yes, there is a difference - but not the way you may be thinking.

It is not that NULL has a data type per se, one will be associated with it (implicitly or explicitly) as part of evaluating the SQL. With the SELECT statement above, the data type applies to the column metadata. Without an explicit CAST, the data type defaults to INT.

Take this query:

<cfquery name="qTest" datasource="#variables.sqlServerDSN#">
    SELECT NULL AS NonSpecifiedNull
        , CAST(NULL AS datetime) AS DateTimeNull
        , CAST(NULL AS varchar(25)) AS VarcharNull
</cfquery>

<cfdump var="#getMetaData(qTest)#" label="Query MetaData">

If you examine the query metadata, the query contains columns with three distinct data types: integer, datetime and varchar:

From a ColdFusion standpoint, the data type impacts how the column values may be interpreted in various functions, comparisons, QoQ's and even when modifying the query object itself. For example, update each of the three columns with a date time object:

<cfset dateTimeNow = now()>
<cfset qTest.NonSpecifiedNull[1] = dateTimeNow>
<cfset qTest.DateTimeNull[1] = dateTimeNow>
<cfset qTest.VarcharNull[1] = dateTimeNow>

<cfdump var="#qTest#" label="Query Values">

The results will be very different. The value inserted into "DateTimeNull" remains a date object. However, the same value will be converted into a string when inserted into "VarcharNull" and an integer when inserted into "NonSpecifiedNull". The latter two are almost certainly not how you would expect, or want, date objects to be handled. That is why it is better to include the appropriate CAST in the original SQL query.

Granted ColdFusion is very forgiving, and relatively typeless. So storing date objects as a string or integer may not always cause hard errors. However, it does force implicit conversion, which is at best unnecessary, at worst prone to error and/or likely to produce the wrong result. For example, if you compared original date to the "NonSpecifiedNull" column, you would probably expect them to be equal, but .. they are not, due to the data type:

dateCompare(dateTimeNow, qTest.NonSpecifiedNull[1]) eq 0 ? "EQUAL" : "DIFFERENT"

So again, best to CAST to the correct type up front to ensure the expected results.



来源:https://stackoverflow.com/questions/37779101/are-there-different-kinds-of-nulls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!