2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SQLServerでゼロサプレスする

Last updated at Posted at 2016-09-11

SQLServerには先頭の0を削除する関数がないので
ストアドファンクションを作成してみました。

CREATE FUNCTION ZeroSuppress (@Target VARCHAR(MAX))
RETURNS VARCHAR(MAX)
AS
BEGIN

  DECLARE @Result AS VARCHAR(MAX)
  SET @Result = '' 

  DECLARE @IsNotZero AS BIT
  SET @IsNotZero = 0

  DECLARE @Counter AS INT
  SET @Counter = 0

  WHILE LEN(@Target) > @Counter
  BEGIN
    IF SUBSTRING(@Target, @Counter + 1, 1) = '0'
      BEGIN
        IF @IsNotZero = 1
          BEGIN
            SET @Result = @Result + SUBSTRING(@Target, @Counter + 1, 1)
          END
      END
    ELSE
      BEGIN
        SET @Result = @Result + SUBSTRING(@Target, @Counter + 1, 1)
        SET @IsNotZero = 1
      END

    SET @Counter = @Counter + 1
  END

  IF @Result = ''
    BEGIN
      SET @Result = '0'
    END

  RETURN @Result
END

これを以下のようにして実行します。

SELECT dbo.ZeroSuppress('000123') AS RESULT

なお、今回使用したバージョンは以下の通りです。
Microsoft SQL Server 2012 Express Edition

2
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?