1

I want to attach numeric value in dynamic query but I am an getting error:

Conversion failed when converting the varchar value ' + @psRegionCode + ' to data type smallint

My query is:

SET @psRegionCode = UPPER(LTRIM(RTRIM(@psRegionCode)))

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

Things which I tried:

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

Can somone please help me with this?

2
  • 1
    Which RDBMS is this for? Please add a tag to specify whether you're using mysql, postgresql, sql-server, oracle or db2 - or something else entirely. Commented May 25, 2016 at 6:39
  • 1
    @marc_s i added additional tag sqlserver Commented May 25, 2016 at 6:47

2 Answers 2

2
 IF (@psRegionCode <> 0)
 BEGIN
     SET @sSQLStr = @sSQLStr + 
         ' AND reg.region_cd = ' + cast(@psRegionCode as nvarchar(10))
  1. you need to make sure you have correct number of apostrophes

  2. if @psRegionCode is number, why you ltrim it? if it is a string why you cast it?

Sign up to request clarification or add additional context in comments.

5 Comments

it was string previously
So now you don't need the first statement, if it is not a string. Is the dynamic sql working?
perhaps you will edit your question with more information about @sSQLStr?
Dear Liya , when i print my Query it print like'' WHERE repStat.rep_state_flg = 'Y' AND reg.region_cd = ' + @psRegionCode + ' it shoud print WHERE repStat.rep_state_flg = 'Y' AND reg.region_cd = 3
why after psRegionCode you still have + ' ? here is an example (I skip variable sign @, becuase it doesn't let me put it here) declare psRegionCode smallint = 2 declare sSQLStr nvarchar(200) set sSQLStr = '' SET sSQLStr = sSQLStr + ' AND reg.region_cd = ' + cast(psRegionCode as nvarchar(10)) select sSQLStr It returns AND reg.region_cd = 2
2

Well, by your syntax I'm guessing SQL-Server? Any way I think your second query should work, you are just missing a parenthesis :

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

You can't concat a number into a string without the conversion.

5 Comments

there is a problem with '
still facing same problem
What type is @psRegionCode ?
@sagi I remove that first line upper lrtim an rtrim but still getting same error
when i print my Query it print like'' WHERE repStat.rep_state_flg = 'Y' AND reg.region_cd = ' + @psRegionCode + ' it shoud print WHERE repStat.rep_state_flg = 'Y' AND reg.region_cd = 3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.