将varchar值转换为数据类型int时转换失败

时间:2010-04-16 15:58:31

标签: sql sql-server tsql

我将varchar(1000)列声明为包含所有数字的字段,如下所示。 我想执行以下脚本。我需要这个才能工作

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

1 个答案:

答案 0 :(得分:6)

您似乎想要使用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

在以这种方式编码时,您需要非常小心关于SQL注入。