I have ID
as a varchar. I need to split as Comma after that i need to convert list to int32. I added example like below.
DECLARE @List varchar(255)
SET @List = '1, 2, 3, 4, 5, 6'
print @List
I have ID
as a varchar. I need to split as Comma after that i need to convert list to int32. I added example like below.
DECLARE @List varchar(255)
SET @List = '1, 2, 3, 4, 5, 6'
print @List
您可以尝试以下方法:
DECLARE @List varchar(255) = '1, 2, 23, 4, 5, 6'
DECLARE @X XML
SELECT @X = '<myxml><nodes><n>' +
REPLACE(@List,',','</n></nodes><nodes><n>') +
'</n></nodes></myxml>'
--SELECT @X
SELECT LTRIM(C.value('n[1]','VARCHAR(50)')) AS item1
FROM @X.nodes('/myxml/nodes') Cols (C)
结果:
| ITEM1 |
--------|--
| 1 |
| 2 |
| 23 |
| 4 |
| 5 |
| 6 |
注意:如果根据您的样本数据 ( ) 在数字之间有空格,则可以在转换为 INT 之前2 3
使用函数将其删除。IsNumeric()函数也可能有用(有关详细信息,请阅读 isNumeric() 函数的注释部分)。Replace()
我已经从pswg 的答案中改编了一个脚本,该脚本将一个字符串拆分为 int 的内存表:
CREATE FUNCTION [dbo].[SplitToIntList]
( @string nvarchar(4000)
, @delim nvarchar(100) )
RETURNS
@result TABLE ([Value] int NULL)
AS
BEGIN
DECLARE @str nvarchar(4000)
, @pos int
, @prv int = 1
SELECT @pos = CHARINDEX(@delim, @string)
WHILE @pos > 0
BEGIN
SELECT @str = SUBSTRING(@string, @prv, @pos - @prv)
INSERT INTO @result SELECT CAST(@str AS INT)
SELECT @prv = @pos + LEN(@delim)
, @pos = CHARINDEX(@delim, @string, @pos + 1)
END
INSERT INTO @result SELECT CAST(SUBSTRING(@string, @prv, 4000) AS INT)
RETURN
END
高温高压