Disclaimer: I am still learning SQL so I apologize if my question comes off as amateur-ish or is otherwise a very simple answer. I have no formal training. I am teaching myself. Thanks.
A particular query was created to update the EMAIL column with data in the EMAIL2 column should the EMAIL column be blank. This query goes on to grab data from the EMAIL3-6 columns should any prior ones also be blank in an attempt to populate the EMAIL column. It currently sits as follows:
update Parents
set email = email2
where email = ' ' OR email is null
go
update Parents
set email = email3
where email = ' ' OR email is null
go
update Parents
set email = email6
where email = ' ' OR email is null
go
(and so on)
Is there a more simple way, using some sort of IF…THEN type conditions to check for blank or null in the EMAIL column and populate it based on data in the secondary column(s)? These columns would also need to be checked for blank or null values and skipped if blank or null is true.
I appreciate any advice that can be given. The above query works it just doesn’t feel like the best way to go about doing it.
A handy function you will want to become aquainted with is NULLIF. It allows you to simplify your logic in cases where you might like to treat a value like a NULL. For example, if an application was putting a sentinel value of ‘NA’ in a NULLable column
column1,NULLIF(column1, 'NA')would return the NULL value for all the NULLs and all the NAs. In your case, we’d use this trick to convert empty strings into NULLs.The other thing we’ll do is trim all the empty strings down so our NULLIF only needs to check for the scenario of ” (instead of ”, ‘ ‘, ‘ ‘, ad nauseum). TSQL only provides LTRIM and RTRIM and I have a habit of using
RTRIMalthough trimming an empty string from either direction will result in our desired state.NULLIF(RTRIM(column1),'')Using that expression, we will now have the right thing to plug into the COALESCE function. Thus