Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

tsql - SQL Server : concat two columns with delimiter if both not nulll else return third column

Here's a sample table

FirstName   LastName   UserName
----------------------------------
Bob         Jones      bjones
null        null       tomroberts
null        Ricardo    rricardo
Robby       null       robroy
George      Glass      gglass

I'm looking for a select that'll return

Jones, Bob
tomroberts
rricardo
robroy
Glass, George

If the first name OR last name are null or empty strings, I want to return the user name. Otherwise I want to return the "lastname, firstname"

Can someone help with the query?

Thanks!

question from:https://stackoverflow.com/questions/66047403/sql-server-concat-two-columns-with-delimiter-if-both-not-nulll-else-return-thi

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

An alternative to using a CASE statement is to use the COALESCE function which returns the first non-NULL argument.

SELECT 
    COALESCE(NULLIF(LastName,'') + ',' + NULLIF(FirstName,''), UserName)
FROM 
  MyTable

Note:- It's important to use the + to concat the columns as this will return NULL if any column contains null. The CONCAT function will return a value that contains the non-NULL parts.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...