I have done some debugging on my sql and I cant figure out the maddening error I am getting I have narrowed it down to a couple of lines which I cant see what the problem is
You are missing about 3 opening brackets as far as i can tell at
select @cols2 = (Select Stuff((Select '],[
and
(' + @cols2 + ']' // -> either [' + @cols2 + ']' or (' + @cols2 + ')'
+ ') SELECT ' + @cols2 + ']' -- -> either ') SELECT [' + @cols2 + ']' or ') SELECT (' + @cols2 + ')'