desi
desi

Reputation: 476

Conversion failed when converting the varchar value to data type int

I have a varchar(1000) column declared as field that contains all numbers, as shown below. And I want to execute the following script. I need this to work please

Declare @PostalCode varchar(1000)=0
    set @PostalCode ='7005036,7004168,7002314,7001188,6998955'

Select hl.* From CountryLocation cl
INNER JOIN refPostalCodes pc ON pc.PostalCode = hl.PostalCode
where pc.Postalcode in (@PostalCode) and pc.notDeleted = 1

Upvotes: 4

Views: 6283

Answers (1)

Austin Salonen
Austin Salonen

Reputation: 50215

It looks like you want to use sp_executesql:

Declare @PostalCode varchar(1000)=0
    set @PostalCode ='7005036,7004168,7002314,7001188,6998955'

declare @sql nvarchar(4000)  //didn't count the chars...

select @sql = N'Select hl.* From CountryLocation cl
INNER JOIN refPostalCodes pc ON pc.PostalCode = hl.PostalCode
where pc.Postalcode in (' + @PostalCode + ') and pc.notDeleted = 1'

exec sp_executesql @sql

You need to be very careful about SQL injection when coding this way.

Upvotes: 7

Related Questions