Error in declare Variable

saravanan d 21 Reputation points
2023-06-01T07:36:55.9566667+00:00

hi ,

i have below query but it shows syntex error


SET @Query = N' SELECT Clientid, clientname,' + @Columns2 + ', Total = ' +REPLACE(@pivv, ',[', '+[') + ' INTO #Tempsara
FROM
(
SELECT Clientid, clientname,toupupamount,CONVERT(VARCHAR,Posteddatekey)+''_Topup'' Typ  FROM #TMP_DATEatt   
UNION  
SELECT Clientid, clientname,Deno  ,CONVERT(VARCHAR,Posteddatekey)+''_DENOCOUNT'' Typ  FROM #TMP_DATEatt AS P  
) AS j
PIVOT
(
  SUM(toupupamount) FOR  Typ  IN ('+ @pivv + ')
) AS p; 
DECLARE @Newcol NVARCHAR(MAX)
 
Select @Newcol=Stuff((Select ''+''+Name FRom Tempdb.sys.columns Where Object_id=Object_id(''tempdb..#Tempsara'' ) AND Name Like ''%_Topup'' For Xml Path('''')),1,1,'''') 
Select *,'+@Newcol+' AS TopupTotal from #Tempsara 
DROP TABLE #Tempsara';
 
EXEC (@Query) 
SQL Server | Other
{count} votes

1 answer

Sort by: Most helpful
  1. Olaf Helper 47,441 Reputation points
    2023-06-01T07:52:29.9533333+00:00

    but it shows syntex error

    And which detailed error message do you get?

    Use a PRINT command to validate your dynamic SQL result.

    https://learn.microsoft.com/en-us/sql/t-sql/language-elements/print-transact-sql?view=sql-server-ver16

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.