Concatenate Column Names using Dynamic SQL

I need to use Dynamic SQL. For the sake of simplicity, I will omit a large portion of the code along with the parameter passing. I have included the part of the code where I receive an error. Part of the result set is two columns concatenated, separtated by a hyphen.

SELECT BranchNumber + ' - ' + BranchName from MyTable
      ....This returns:   5050 - Boston

But I get a syntax error on this portion when using dynamic SQL.

exec ('SELECT BranchNumber' + ' - '  + 'BranchName from MyTable')

**BranchNumber and BranchName are both varchar
Who is Participating?
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.


I think it was to do with the way you are building the string

try this instead

exec ('SELECT BranchNumber + '' - '' + BranchName from MyTable')


Try to use 2 single quotes instead of 1 around the - and you don't need the quotes after Brachnumber and before Branchname.

This is because for the EXEC statement you create a string

exec ('SELECT BranchNumber + ''- ''  + BranchName from MyTable')

If you print your statement above, you'll see that your trying to execute the following line...

SELECT BranchNumber - BranchName from MyTable

SQL thinks you're trying to subtract BranchName from BranchNumber...

Try this...

EXEC ('SELECT BranchNumber + '' - ''  + BranchName from MyTable')

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
jvoconnellAuthor Commented:
Thank you all. All statements worked and  I got a little more knowledge from all of you.

Thanks a million!!
Glad you learnt something aswell as got your answer! :)


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
Microsoft SQL Server

From novice to tech pro — start learning today.