简体   繁体   中英

Param error in where clause when executing sp_executesql

I searched for an answer but I didn't find anything. How to resolve this error?

Msg 137, Level 15, State 2, Line 10
Must declare the scalar variable "@SDP".

This is my code:

declare @SQL NVARCHAR(4000),
        @dfilter NVARCHAR(100)
        @SDP DateTime

set @dfilter = 
        (case when @SDP is null 
            then '@SDP BETWEEN CAST(sp.StartDate AS DATE) AND CAST(sp.EndDate AS DATE) '
            else '@SDP = CAST(sp.StartDate AS DATE) '
         end)

set @SQL = N'UPDATE p SET PriceWithVAT = promo.Price, IsPromo=1  
             FROM #preturi p  
             JOIN 
                 (SELECT pp.ItemId, Price   
                  FROM SalesPromotion sp (NOLOCK)  
                  JOIN SalesPromotionXSite sps (NOLOCK) ON sp.SalesPromotionId = sps.SalesPromotionId  
                  JOIN SalesPromotionDetail spd (NOLOCK) ON sps.SalesPromotionId = spd.SalesPromotionId  
                  JOIN #preturi pp on pp.ItemId = spd.ItemId  
                  WHERE sps.SiteId = '+quotename(@SiteId)+    
                ' AND spd.IsActive = 1 AND ' + @dfilter+
                ') promo ON p.ItemId = promo.ItemId'

 BEGIN
     EXEC sp_executesql @SQL 
 END

First, correct the syntax (in the DECLARE statement is missing ',') and declare @SiteId .

After that, note that you are using @SDP variable in T-SQL statement, so you must send this variable to sp_executesql :

...
EXEC sp_executesql @SQL, N'@SDP DateTime', @SDP

Thank you Zhorow. Whit this answer, I replaced

WHERE sps.SiteId = '+quotename(@SiteId)+

with

WHERE sps.SiteId = @SiteId' 

and I ran

EXEC sp_executesql @SQL, N'@StartDataPret DateTime, @SiteId int', @StartDataPret, @SiteId

it working wonderfull

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM