Sqlserver
 sql >> Teknologi Basis Data >  >> RDS >> Sqlserver

Bagaimana cara mengurutkan string menurut abjad

Bahkan beberapa kemungkinan yang dioptimalkan ada di sana. Di sini dua fungsi menggunakan Bubble sort untuk mengurutkan karakter.

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

Fungsi 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, (@[email protected])-1)
               SET @end = SUBSTRING(@fullstring, @charlocation2+1, @len)
               SET @returnval = @begin + @secondchar + @middle + @firstchar + @end
        END
    RETURN(@returnval)
END

Hasil:

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

--Referensi

--Demo cepat di sini



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. SQL Server Profiler - Bagaimana cara memfilter jejak untuk hanya menampilkan acara dari satu database?

  2. MS SQL 2008 - dapatkan semua nama tabel dan jumlah barisnya dalam DB

  3. Impor Tanggal String di kolom Derived

  4. TSQL Split node XML

  5. Indeks SQL Server:Persyaratan utama, dampak kinerja, dan pertimbangan