简体   繁体   中英

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

You have two methods to handle this, dynamic SQL and splitting the string.

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"):

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

The dynamic SQL looks like:

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. If you leave it out, then the default varies by context -- and your code may not do what you expect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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