Sunday 7 July 2013

ColdFusion cfqueryparam NULL Value

When you query a database with ColdFusion and your result set contains null values ColdFusion represents those values as an empty string. This is great as long as you're aware of it, you can just check the length of the string and if it's greater than 0 you know it isn't null and isn't empty.

The problem is what do you do when you want to insert or update a null into the database? If the value will always be null you can just hard code it like this...
However this doesn't help us in most cases where the value could contain something or it could be null. To do this we need to use the "null" attribute of the cfqueryparam tag. If the null attribute is set to false nothing happens and the value is used as normal. However if the null attribute is set to true, the value attribute is ignored and a null is sent to the database.

In this example if the length of the address passed in from the form is greater than 0 the value is used. However if the length is 0, the value is ignored and null is sent to the database.

Also note that this functionality is available in cfscript as shown below...