我正在尝试使用 TSQL 将“3,9,6”等字符串排序为“3,6,9”。我的方法是从字符串中提取字符,将它们转换为整数,然后使用主键将它们放入 #temptable 中进行排序。为此,我创建了这个过程:
create proc sortstring(@string varchar(50))
as
declare @limit int = len(@string)
declare @counter int = 1
declare @temps char
create table #temptable (tempstring varchar(30) primary key)
while @counter<=@limit
begin
set @temps = SUBSTRING(@string,@counter,1)
if(@temps!=',')
insert into #temptable values (CAST(@temps as int))
set @counter= @counter+1
end
在此过程之后,我正在考虑使用 while 循环从 #temptable 中提取整数,以创建排序的字符串格式“3,6”9'。但我认为我的整个方法性能效率不高。
有什么建议吗?
最佳答案
下面的方法应该比 while 循环好一点
declare @string varchar(255) = '3,9,6,0,5,12,88,15,23,45,77,88,125,1'
declare @TableList table (tmpStr int)
DECLARE @XML XML
SET @XML = '<root><csv>' + replace(@string, ',', '</csv><csv>') + '</csv></root>'
INSERT @TableList
SELECT replace(Word.value('.', 'integer'), CHAR(10), '')
FROM @XML.nodes('/root/csv') AS WordList(Word)
select * from @TableList order by 1
go
关于mysql - 使用 TSQL 对字符串中的整数进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35026245/