I'm using this SQL code:
DECLARE
@vals AS varchar(MAX),
@q  AS varchar(MAX)
select @vals = STUFF((SELECT distinct ',' + QUOTENAME(chgnum) 
        from pppview_nl
        FOR XML PATH(''), TYPE
    ).value('.', 'varchar(MAX)'),1,1,'')
set @q = 'SELECT lotdetid,' + @vals + ' FROM 
                        (
                SELECT TOP 50 lotdetid, LineValue as val,chgnum FROM pppview_nl ORDER BY lotdetid DESC
                        ) a
                        pivot 
                        (
                            max(val)
                            for chgnum in (' + @vals + ')
                        ) b'
execute(@q)
Which works fine, and changes:
https://i.stack.imgur.com/yPd9a.png
INTO:
https://i.stack.imgur.com/vDOgI.png
It runs fine on Navicat and SQL Fiddle, but when I try and save it, I get this issue: [SQL Server]Incorrect syntax near the keyword 'DECLARE'
I've done quite a bit of reading and far from redoing the entire thing, how can this issue be fixed? I read something somewhere about needing to but all declares inside a ~~whatever it was~~ but then other people are seeming saying it doesn't make a difference.
Hope someone can assist me in this, as it's a bit of a head-scratcher how it works fine but doesn't save.
Regards, Oscar.
Edit:
ALTER PROCEDURE [dbo].[o_getvals]
    @lotdetit varchar(6)
AS
BEGIN
    DECLARE
    @vals AS varchar(MAX),
    @q  AS varchar(MAX)
    select @vals = STUFF((SELECT distinct ',' + QUOTENAME(chgnum) 
            from pppview_nl
            ORDER BY chgnum desc
            FOR XML PATH(''), TYPE
        ).value('.', 'varchar(MAX)'),1,1,'')
    set @q = 'SELECT lotdetid,' + @vals + ' FROM 
                            (
                                    SELECT TOP 50 lotdetid, LineValue as val,chgnum FROM pppview_nl WHERE lotdetid = ' + @lotdetit + ' ORDER BY lotdetid DESC
                            ) a
                            pivot 
                            (
                                max(val)
                                for chgnum in (' + @vals + ')
                            ) b'
    execute(@q)
END
Stored proceedure did the trick, thanks jyparask and everyone else. :)
 
     
    