如何按字母顺序排序字符串

时间:2014-12-12 12:06:34

标签: sql-server sql-server-2008 sorting sql-server-2008-r2

我是SQL Server的新手,也是Stack溢出的新手。请原谅我的错误。

是否可以按字母顺序对列中的值进行排序?这是我的表

NAME
......
XZYVW
EBACD

我的结果应如下所示

NAME
......
VWXYZ
ABCDE 

有什么想法吗?

4 个答案:

答案 0 :(得分:5)

甚至还有一些优化的可能性。这里有两个函数使用冒泡排序来对char进行排序。

CREATE FUNCTION udf_SortString
(
    @string VARCHAR(1000)
)
RETURNS VARCHAR(1000)
AS
BEGIN
    DECLARE @len TINYINT
    DECLARE @i TINYINT
    DECLARE @currentchar CHAR(1)
    DECLARE @swapped BIT
    DECLARE @begin BIT
    DECLARE @nextchar CHAR(1)

    SET @begin = 1
    SET @len = LEN(@string)
    SET @i = 1

    WHILE @begin = 1 OR @swapped = 1
    BEGIN
        SET @swapped = 0
        SET @i = 1
        SET @begin = 0
        WHILE @i <= @len
        BEGIN
            SET @currentchar = SUBSTRING(@string, @i, 1)
            SET @nextchar = SUBSTRING(@string, @i + 1, 1)

            IF @currentchar > @nextchar AND (@nextchar > '')
            BEGIN
                SET @string = dbo.udf_swap(@string, @i, @i + 1)
                SET @swapped = 1
            END

            SET @i = @i + 1
        END
    END

    RETURN(@string)
END

功能2:

CREATE FUNCTION dbo.udf_Swap
(
    @fullstring VARCHAR(1000),
    @charlocation1 TINYINT,
    @charlocation2 TINYINT
)
RETURNS VARCHAR(1000)
AS
BEGIN
        DECLARE @returnval varchar(1000)
        DECLARE @begin VARCHAR(1000), @middle VARCHAR(1000), @end VARCHAR(1000)
        DECLARE @firstchar CHAR(1), @secondchar CHAR(1), @len INT
        SET @fullstring = LTRIM(RTRIM(@fullstring))
        SET @len = LEN(@fullstring)

    IF @charlocation1 > @len OR @charlocation2 > @len
        SET @returnval = @fullstring
        ELSE
        BEGIN
               SET @firstchar = SUBSTRING(@fullstring, @charlocation1, 1)
               SET @secondchar = SUBSTRING(@fullstring, @charlocation2, 1)
               SET @begin = LEFT(@fullstring, (@charlocation1-1))
               SET @middle = SUBSTRING(@fullstring, @charlocation1+1, (@charlocation2-@charlocation1)-1)
               SET @end = SUBSTRING(@fullstring, @charlocation2+1, @len)
               SET @returnval = @begin + @secondchar + @middle + @firstchar + @end
        END
    RETURN(@returnval)
END

结果:

select dbo.udf_SortString('zxcvbfgrtyuijklm')
--Returns bcfgijklmrtuvxyz

--Reference

--Quick demo here

答案 1 :(得分:2)

创建User Defined Scalar Function.

CREATE FUNCTION dbo.Alphaorder (@str VARCHAR(50))
returns VARCHAR(50)
  BEGIN
      DECLARE @len    INT,
              @cnt    INT =1,
              @str1   VARCHAR(50)='',
              @output VARCHAR(50)=''

      SELECT @len = Len(@str)
      WHILE @cnt <= @len
        BEGIN
            SELECT @str1 += Substring(@str, @cnt, 1) + ','

            SET @cnt+=1
        END

      SELECT @str1 = LEFT(@str1, Len(@str1) - 1)

      SELECT @output += Sp_data
      FROM  (SELECT Split.a.value('.', 'VARCHAR(100)') Sp_data
             FROM   (SELECT Cast ('<M>' + Replace(@str1, ',', '</M><M>') + '</M>' AS XML) AS Data) AS A
                    CROSS APPLY Data.nodes ('/M') AS Split(a)) A
      ORDER  BY Sp_data

      RETURN @output
  END

<强>结果:

SELECT dbo.Alphaorder ('XZYVW') --VWXYZ

答案 2 :(得分:2)

这将按字母顺序对字母进行排序,而不使用函数。在@Shnugo评论

之后重写以进行优化
DECLARE @t table(col varchar(4000))
INSERT @t values('kdjfh'),('zug')

SELECT
  Col, 
  (
    SELECT
      chr
    FROM
      (SELECT TOP(LEN(Col)) 
         SUBSTRING(Col,ROW_NUMBER() OVER(ORDER BY 1/0),1)
       FROM sys.messages) A(Chr)
       ORDER by chr
       FOR XML PATH(''), type).value('.', 'varchar(max)'
      ) SortedCol
FROM
  @t

结果:

col    SortedCol
kdjfh  dfhjk
zug    guz

答案 3 :(得分:0)

不是mssql,但是在Presto中,我发现了这种方式。也许有人可以将其转换,或者找到一种更好的方式将字符串拆分为数组,排序并重新加入:

describe('MyComponent ', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;

  beforeEach(async(() => {
      TestBed.configureTestingModule({
          declarations: [MyComponent],
          imports: [
              ...
      ],
          providers: [
          ],
      }).compileComponents().then(() => {
          fixture = TestBed.createComponent(MyComponent);
          component = fixture.componentInstance;
      });
  }));

  describe('Should initialize Base grid', () => {
    const baseGridSpecs = new BaseGridSpecs<ComponentModel>();

    beforeEach(() => {
      baseGridSpecs.component = component;
      baseGridSpecs.fixture = fixture;          
    });

    // Here for me dummyData is model's object with proper value, 
    // which I can use to check service based calls.
    baseGridSpecs.loadSpecs(dummyData);
  });
});