本文介绍了如何反转列中的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 varchar(128) 列的表,其中包含以下数据:

I have a table with varchar(128) column with data like:

word1, word2, , word3, word4
word1, word2, word3, ,
word1,,,, ;word2
;word1 word2, word3

word1, word2, , word3, word4
word1, word2, word3, ,
word1,,,, ; word2
;word1 word2, word3

我必须更新这个表格,让单词倒序:

I have to update this table, making words reverse order:

word4, ,word3,,word2 ,word1
,,word3, ,word2, word1

word4, ,word3,,word2 ,word1
,,word3, ,word2, word1

你能帮我只用一个 sql 查询吗?

Could you help me to do it using only single sql query??

推荐答案

要完成此任务将需要一个 t-sql 函数和一个游标.fn_SplitList 将允许您根据分隔符进行拆分.一旦你有了这个函数,你就可以创建一个游标来运行你的数据更新每条记录.我使用@table1 创建了一个示例.

To accomplish this task will require a t-sql function and a cursor. fn_SplitList will allow you to split based on a delimiter. Once you have this function you can create a cursor to run against your data updating each record. I created an example using @table1.

功能

CREATE FUNCTION [dbo].[fn_SplitList]
(
    @RowData varchar(8000),
    @SplitOn varchar(5)
)
RETURNS @RtnValue table
(
    Id int identity(1,1),
    Data varchar(100)
)
AS
BEGIN
    Declare @Cnt int
    Set @Cnt = 1

    While (Charindex(@SplitOn,@RowData)>0)
    Begin
        Insert Into @RtnValue (data)
        Select
            Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))

        Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
        Set @Cnt = @Cnt + 1
    End

    Insert Into @RtnValue (data)
    Select Data = ltrim(rtrim(@RowData))

    Return
END

执行更新的代码

declare @table1 table(id int primary key
                     ,words varchar(max))
declare @id int
declare @words varchar(max)

insert into @table1 values(0, 'word1, word2, , word3, word4')
insert into @table1 values(1, 'word1, word2, word3, ,')
insert into @table1 values(2, 'word1,,,, ; word2')
insert into @table1 values(3, ';word1 word2, word3')

declare updateCursor cursor for
select id
      ,words
  from @table1

open updateCursor
fetch next from updateCursor into @id, @words
while @@fetch_status = 0
begin
  declare @row varchar(255)

  select @row = coalesce(@row+', ', '') + data
    from dbo.fn_SplitList(@words, ',')
  order by id desc

  update @table1
     set words = @row
   where id = @id

  fetch next from updateCursor into @id, @words
end
close updateCursor
deallocate updateCursor

select *
  from @table1

这篇关于如何反转列中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 16:29