Help with a SQL String

Hello EE,

I have this string in SQL query :

[KeyCode] = Sub_Level_Key1 + '-' + isnull(Sub_Level_Key2, '') + '-' + isnull(Sub_Level_Key3, '')

returns something like:    01-02-03

my problem is if key2 or/and key3 are null it would be like:   01--

I need  a way that if key2 and key3 are null that I do not show the dashes.

so It would be  :   01

or :    01-03
or :    01-06-03

key2 wont be null be key3 is not null.

any idea?
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

User CASE:
Sub_Level_Key1 + CASE WHEN Sub_Level_Key2 IS NULL THEN '' ELSE '-' + Sub_Level_Key2 END + CASE WHEN Sub_Level_Key3 IS NULL THEN '' ELSE '-' + Sub_Level_Key3 END

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
there may be a better way, but this will work:

[KeyCode] = replace( Sub_Level_Key1 + '-' + isnull(Sub_Level_Key2, '') + '-' + isnull(Sub_Level_Key3, ''), '--', '-' )
just do like this

[KeyCode] = Sub_Level_Key1 + isnull('-' + Sub_Level_Key2, '') + isnull('-' + Sub_Level_Key3, '')
Protecting & Securing Your Critical Data

Considering 93 percent of companies file for bankruptcy within 12 months of a disaster that blocked access to their data for 10 days or more, planning for the worst is just smart business. Learn how Acronis Backup integrates security at every stage

PhilippeRenaudAuthor Commented:
Thanks. totally forgot the case when..
oh well.
ralmada, yours could never work, because
'-' + NULL
 is always
so it would never be null.
actually '-' + null is always null
Oh. I stand corrected then. Ralmada's code is a good alternative, then.
PhilippeRenaudAuthor Commented:
I tried the first comment by the way and it worked and forgot about testing the others
I could had give points to others also.

but thank you for all the help and attention
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Query Syntax

From novice to tech pro — start learning today.