Skip to content Skip to sidebar Skip to footer

Using Variable With Dynamic Sql

Hi I am using Dynamic Query in My store Procedure Using following syntax ` set @query =N'Select ComponentName, '+ @cols +' From ( Select Sum('+ @Sum_cols +') As Comp_s

Solution 1:

You have the line AND ( @BG = ''''OR COM.BGName =''' + @BG +'''. `@BG' isn't declared in your Dynamic SQL. You need to pass it like you did later in the same line:

AND   ( '' +  @BG + '' = '''' OR  COM.BGName =''' + @BG +'''

This query, however, appears to be open to SQL injection; you would be much better off parametrising it:

SET@query= N'
SELECT ComponentName,
        '+@cols+ N'  --This might need to be changed as well, but i don''t know how you''re generating this and I''m not guessing
FROM (SELECT SUM(('+@Sum_cols + N') AS Comp_stock, --This might need to be changed as well, but i don''t know how you''re generating this and I''m not guessing
             Com.ComponentName,
             BB.BB_Name  
      FROM Z_DM_DR_CM_STOCK COM
           INNER JOIN BLOOD_BANK_MASTER BB ON COM.BB_srno =BB.BB_SRNO
      WHERE Com.Trans_date = @sTrans_date
        AND (@sBG = '''' OR COM.BGName = @sBG )
      GROUP BY Com.ComponentName,
               BB.BB_Name) AS sourcetable 
PIVOT (
    --This might need to be changed as well, but i don''t know how you''re generating this and I''m not guessing
    SUM([Comp_stock]) FOR [BB_Name] IN ('+@cols+ N')) AS PIVOTTABLE
ORDER BY ComponentName';

EXEC sp_executesql @query, N'@sBG int, @sTrans_date date', @sBG=@BG, @sTrans_Date =@trans_date; --I have guessed your data types

Note (as I know people have a habit of not reading comments people leave for them in their code) I have no idea what the data type for @BG and @Trans_date is, thus I have geussed they are int and daterespectively. You'll need to changed this, if i have guessed incorrectly.

You can see from the comments that you need to looks at how you add the values of the columns to your query as well; the way you've done it may also be open to injection, but i haven't seen the earlier part of your query.

Post a Comment for "Using Variable With Dynamic Sql"