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

Hapus nilai duplikat dalam sel SQL Server

Coba ini.

CREATE FUNCTION STR_Func (@Str AS VARCHAR(100))
RETURNS VARCHAR(Max)
AS
  BEGIN
      DECLARE @count   INT,
              @tempstr VARCHAR(100)='',
              @nLength INT,
              @outstr  VARCHAR(100)=''

      SET @count=1
      SET @Str = Replace(@Str, '/', '')
      SET @nlength = Len(@Str)

      WHILE ( @count < @nLength )
        BEGIN
            SET @[email protected] + Substring(@Str, 1, 1)
            SET @Str=Replace(@Str, Substring(@Str, 1, 1), '')
            SELECT @outstr = @outstr + RIGHT(@tempstr, 1) + '/'
            SET @[email protected] + 1
        END

      RETURN LEFT(@outstr, Len(@outstr) - 1)
  END 

select dbo.STR_Func('B/A/C/A')

OUTPUT : B/A/C

Jika Anda ingin menghapus duplikat dan jika tidak peduli dengan urutannya, coba ini.

DECLARE @code  VARCHAR(100)='B/A/C/A',
        @code1 VARCHAR(100)=''


SELECT @code1 += '/' + splitrow
FROM   (SELECT DISTINCT Split.a.value('.', 'VARCHAR(100)') splitrow
        FROM   (SELECT Cast ('<M>' + Replace(@code, '/', '</M><M>') + '</M>' AS XML) AS Data) AS A
               CROSS APPLY Data.nodes ('/M') AS Split(a)) b

SELECT RIGHT(@code1, Len(@code1) - 1) 

KELUARAN :A/B/C



  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 - gabungkan baris ke dalam daftar yang dipisahkan koma

  2. datetime vs smalldatetime di SQL Server:Apa Bedanya?

  3. ExecuteScalar vs ExecuteNonQuery saat mengembalikan nilai identitas

  4. SQL Server 2008 GEOGRAFI STDistance() nilai

  5. Perbedaan Antara Fungsi Bernilai Tabel Multi-Pernyataan &Fungsi Bernilai Tabel Sebaris di SQL Server