简体   繁体   English

在T-SQL中将字符串中的int转换为整数

[英]Convert int in string to integers in T-SQL

I need to convert string to integers, but I'm getting a type error. 我需要将字符串转换为整数,但出现类型错误。

declare @stringinteger nvarchar(255) null;
set @stringinteger='1,2,3,4'

select *
from user
where id in (@stringinteger) 

The error I get: 我得到的错误:

Conversion failed when converting the nvarchar value '1,2,3,4' to data type int 将nvarchar值'1,2,3,4'转换为数据类型int时转换失败

You have two methods to handle this, dynamic SQL and splitting the string. 您有两种方法可以处理此问题,即动态SQL和拆分字符串。

For the latter, you can use string_split() (introduced in SQL Server 2016) or a similar function (they are all over the web, google "string split sql server"): 对于后者,您可以使用string_split() (在SQL Server 2016中引入)或类似的功能(它们在整个网络上,谷歌“字符串拆分sql服务器”):

select *
from user
where id in (select cast(value as int) from string_split(@stringinteger, ',')) ;

The dynamic SQL looks like: 动态SQL看起来像:

declare @stringinteger nvarchar(255) null;
set @stringinteger = '1,2,3,4';

declare @sql nvarchar(max);
set 'select *
from user
where id in (@stringinteger)';

set @sql = replace(@sql, '@stringinteger', @stringinteger);

exec sp_executesql @sql;

Note that in SQL Server, you should always provide a length for character types. 请注意,在SQL Server中,应始终提供字符类型的长度。 If you leave it out, then the default varies by context -- and your code may not do what you expect. 如果不加说明,则默认值会因上下文而异-代码可能无法达到您的期望。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM