执行sp_executesql时where子句中的参数错误

时间:2018-06-27 09:01:29

标签: sql sql-server parameters where-clause sp-executesql

我搜索了答案,但没有找到任何答案。如何解决此错误?

  

第13级州立2行10的消息137
  必须声明标量变量“ @SDP”。

这是我的代码:

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

2 个答案:

答案 0 :(得分:2)

首先,更正语法(在DECLARE语句中缺少',')并声明@SiteId

之后,请注意,您正在T-SQL语句中使用@SDP变量,因此必须将此变量发送到sp_executesql

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

答案 1 :(得分:0)

谢谢卓尔。 惠特这个答案,我替换了

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

WHERE sps.SiteId = @SiteId' 

我跑了

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

效果很好