如何增加数量?

时间:2014-01-05 06:36:23

标签: sql sql-server

ALTER PROCEDURE [dbo].[K_FS_GenerateAutoDCNo] 
AS
BEGIN
  SET NOCOUNT ON;

  DECLARE @dcno VARCHAR(50), @latestindent VARCHAR(50)

  SET @dcno = (SELECT '0000')
  SET @latestindent = (SELECT dcno FROM K_FS_GenerateDcno 
                       WHERE sno = (SELECT max(sno)     
                                    FROM K_FS_GenerateDcno))

  IF EXISTS (SELECT dcno FROM K_FS_GenerateDcno WHERE dcno in (@dcno))
  BEGIN
     SELECT (@latestindent + 1) AS dcno 
  END 
  ELSE 
     SELECT (@dcno) AS dcno
END

首次显示0000,下次显示1

但我想显示0001 ..我该怎么做?

请帮帮我

1 个答案:

答案 0 :(得分:2)

左侧填充0 s最多四位

的值
RIGHT(REPLICATE('0', 4) + CAST(@dcno AS VARCHAR), 4)

这是 SQLFiddle 演示


您的程序可归结为一个陈述

CREATE PROCEDURE K_FS_GenerateAutoDCNo
AS
SELECT RIGHT(REPLICATE('0', 4) + CAST(CAST(COALESCE(MAX(dcno), 0) AS INT) + 1 AS VARCHAR), 4) dcno
  FROM
(
  SELECT TOP 1 dcno 
    FROM K_FS_GenerateDcno
   ORDER BY sno DESC
) q;

这是 SQLFiddle 演示


  

我添加这一行..?

在您的代码中,您可以更改

select (@latestindent + 1) as dcno 

SELECT RIGHT(REPLICATE('0', 4) + CAST(@latestindent + 1 AS VARCHAR), 4) dcno

注意 此类递增方法不是并发安全的,并且受竞争条件限制。