SQL Server 2008 R2: Execute a Dynamic SQL Statement of more than 10,000 characters

I am busy completing a tracking table change stored procedure.  The code is running pretty good with small tables (tables with less fields).
I am facing a problem where the dynamic sql statement  size is more than 8000 characters.
I even tried to break it into small pieces like EXEC (@stmt1 + @stmt2 + @ stmt3 + @stmt4), but still can't beat it.
Any input is welcome.
Note: The sql  involves the use of UNPIVOT and related fields list comes from a variable, and is formated in a way where It allows conversion of all fields to VARCHAR.
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.

Kyle AbrahamsSenior .Net DeveloperCommented:
are you sure that the query prints out exactly as is?

you sohuld be able to use the
EXEC (@stmt1 + @stmt2 + @ stmt3 + @stmt4) format . . . but make sure you leave spaces so that it combines correctly into one query.

I've read that sys.sp_sqlexec will take a text and overcomes the 8000 character limit, though under the hood it just converts the text into a varchar so not sure why it would work with > 8000 but it's worth a shot.


SThayaTechnical MAnagerCommented:

try the below way

declare @query nVarchar(max)
SET @Query =  'SELECT col1,col2......'-- some of the query gets set here
                          + 'col10,col35...'
                          + 'col10,col35...'-- more query gets added on, etc

finally Print @query

sp_exeutesql (@query)


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
Omer-PitouAuthor Commented:
This works finally: EXEC (@stmt1 + @stmt2 + @stmt3 + @stmt4) .
I was missing something in the previous test.
Thanks for your time
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 2008

From novice to tech pro — start learning today.