动态查询SQL where condition

时间:2016-05-25 06:31:42

标签: sql sql-server

我想在动态查询中附加数值,但我收到错误:

  

转换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

请你帮帮我吗?

2 个答案:

答案 0 :(得分:2)

那么,根据你的语法我猜SQL-Server?无论如何我认为你的第二个查询应该有效,你只是缺少一个括号:

IF (@psRegionCode <> 0)
BEGIN
    SET @sSQLStr = @sSQLStr + 
        ' AND reg.region_cd = ' + cast(@psRegionCode as nvarchar(10)) 
END 

如果没有转换,您无法将数字连接到字符串中。

答案 1 :(得分:2)

[root@localhost ivrserver]# pprof --text ./IvrServer ivr.prof
Using local file ./IvrServer.
Using local file ivr.prof.
substr outside of string at /usr/local/bin/pprof line 3695.
Use of uninitialized value in string eq at /usr/local/bin/pprof line 3695.
substr outside of string at /usr/local/bin/pprof line 3697.
Use of uninitialized value in string eq at /usr/local/bin/pprof line 3697.
ivr.prof: header size >= 2**16
  1. 你需要确保你有正确的撇号数

  2. 如果@psRegionCode是数字,你为什么要这么做?如果它是一个字符串为什么你施展它?