如何使用逗号和双撇号(") 转换 nvarchar



我有带有列注释的表作为 nvarchar,当我尝试将 nvarchar 转换为 int 时,我收到类似错误 将 varchar 值"2、9、10、25"' 转换为数据类型 int 时转换失败 你们能帮我吗

如果您使用的是SQL Server 2016,则可以使用String_Split,否则您需要执行一些xml处理才能拆分,如下所示:

;With cte as (
Select xm = CAST('<x>' + REPLACE((SELECT REPLACE(REPLACE(col1,'"',''),', ','$$$SSText$$$') AS [*] FOR XML PATH('')),'$$$SSText$$$','</x><x>')+ '</x>' AS XML) 
from #test  
) Select [Value] from cte c
cross apply ( Select y.value(N'text()[1]', N'int') as value 
FROM c.xm.nodes(N'x') as x(y) ) a

您的输入表

create table #test (col1 nvarchar(20))
insert into #test (col1) values ('"2, 9, 10, 25"' )

最新更新