數字左側補0至指定長度的SQL語法如下
RIGHT(REPLICATE('0', 指定長度) + CAST('123' AS NVARCHAR), 指定長度)
例:RIGHT(REPLICATE('0', 10) + CAST('123' AS NVARCHAR), 10)
~~自動取號的部分~~
假如ID為英文2位數+數字10位數的組合
例:ID0000000001
首先先宣告變數
declare @new_id varchar(20)
接下來就重點戲了,查詢目前取號的最大值並拆解ID的數字部分+1後組裝回去
看一下現在取到第幾號及新的號碼是否正常
SELECT TOP(1) id AS '目前號碼', LEFT(id,2) + RIGHT(REPLICATE('0', 10) + CAST(CAST(RIGHT(id, 10) AS int) + 1 AS NVARCHAR), 10) AS '取新號碼' FROM ID_List ORDER BY id DESC
指派變數的值
set @form_id = (SELECT TOP(1) LEFT(id,2) + RIGHT(REPLICATE('0', 10) + CAST(CAST(RIGHT(id, 10) AS int) + 1 AS NVARCHAR), 10) FROM ID_List ORDER BY id DESC)
就可以使用變數來INSERT、UPDATE了