简体   繁体   English

如何将NVARCHAR逗号分隔列表转换为INT?

[英]How to convert NVARCHAR comma-delimited list to INT?

Is there a way to do the following in SQL Server: 有没有一种方法可以在SQL Server中执行以下操作:

DECLARE @list nvarchar(MAX) = '1, 2, 3, 4, 5, 6';
SELECT * FROM table WHERE ID IN ( @list );

-- Column ID is type bigint

Error: 错误:

Error converting data type nvarchar to bigint. 将数据类型nvarchar转换为bigint时出错。

You don't want to convert it to an int. 您不想将其转换为int。 Instead, use like for the comparison: 而是使用like进行比较:

select *
from table
where ', '+@list+', ' like ', '+cast(id as varchar(255)) + ', ';

This has the downside that the query will not use indexes. 不利之处在于查询将不使用索引。 If that is important, then you can use dynamic SQL: 如果那很重要,那么可以使用动态SQL:

DECLARE @list nvarchar(10) = '1, 2, 3, 4, 5, 6';
declare @sql nvarchar(max) = 'SELECT * FROM table WHERE ID IN ('+ @list +')';

exec sp_executesql @sql;

use Dynamic SQL . 使用Dynamic SQL

DECLARE @SQLQuery AS NVARCHAR(500)
DECLARE @list nvarchar(10) = '1, 2, 3, 4, 5, 6';

SET @SQLQuery = 'SELECT * FROM table WHERE ID IN (' + @list + ')'
EXECUTE(@SQLQuery)

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

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