简体   繁体   中英

if then else to return value in existing column

In Access 2016 using SQL. I need to add a new column called "Customer". The value is based on if there is data in "Group Name" then use "Group Name". If "Group Name" is blank then use the data in "Description".

This is what I'm trying to use and it's not working.

SELECT iIf(ISempty([group name])= FALSE,[Group name],[Description]) as Customer

The solution has to be using SQL as once it works in Access it is used in another software. I am pretty new to this so any help will be greatly appreciated.

The IsEmpty Function "Returns a Boolean value indicating whether a variable has been initialized."

When you apply that function to your [Group name] field, it will always return False, which means this IIf() expression will always give you [Group name] ...

SELECT IIf(ISempty([group name])= FALSE,[Group name],[Description]) as Customer

You explained that you actually want IIf() to give you [Group name] when it is not Null, or [Description] otherwise. To do that, you can substitute IsNull() for IsEmpty() :

SELECT IIf(IsNull([Group name])=False, [Group name], [Description]) As Customer

Here are a couple other ways to accomplish the same thing:

SELECT IIf([Group name] Is Null, [Description], [Group name]) As Customer
SELECT Nz([Group name], [Description]) As Customer

Oops! You actually said "blank" , but I interpreted that to mean Null. If blank could also mean an empty string, use this to give you [Description] when [Group name] contains either Null or an empty string ...

SELECT IIf(Len([Group name] & '') = 0, [Description], [Group name]) As Customer

In ANSI SQL this can be done in two update statements:

-- First replace empty [Customer] with [Group Name]
Update [TargetTable] Set [Customer] = [Group Name]
Where [Customer] IS NULL OR [Customer] = '';

-- Then replace still empty [Customer] with [Description]
Update [TargetTable] Set [Customer] = [Description]
Where [Customer] IS NULL OR [Customer] = '';

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