[英]Dynamic query SQL where condition
我想在动态查询中附加数值,但出现错误:
将varchar值'+ @psRegionCode +'转换为数据类型smallint时,转换失败
我的查询是:
SET @psRegionCode = UPPER(LTRIM(RTRIM(@psRegionCode)))
IF (@psRegionCode <> 0)
BEGIN
SET @sSQLStr = @sSQLStr + ' ' + 'AND reg.region_cd = ''' + @psRegionCode + ''''
END
我尝试过的事情:
SET @psRegionCode = UPPER(LTRIM(RTRIM(@psRegionCode)))
IF (@psRegionCode <> 0)
BEGIN
SET @sSQLStr = @sSQLStr + ' ' +
'AND reg.region_cd = ' + cast(@psRegionCode as nvarchar(10) ''
END
somone可以帮我这个忙吗?
好吧,根据您的语法,我正在猜测SQL Server? 我认为您的第二个查询应该以任何方式工作,您只是缺少括号:
IF (@psRegionCode <> 0)
BEGIN
SET @sSQLStr = @sSQLStr +
' AND reg.region_cd = ' + cast(@psRegionCode as nvarchar(10))
END
如果不进行转换,则无法将数字连接成字符串。
IF (@psRegionCode <> 0)
BEGIN
SET @sSQLStr = @sSQLStr +
' AND reg.region_cd = ' + cast(@psRegionCode as nvarchar(10))
您需要确保正确的撇号数量
如果@psRegionCode是数字,为什么要精简它? 如果是字符串,为什么要强制转换?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.