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

Hi,
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.
Omer-PitouAsked:
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.

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.

eg:

sys.sp_sqlexec(@myTextVar)
0
SThayaTechnical MAnagerCommented:
hi,

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)


{edit}
0

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
0
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.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.