爲什麼使用Numeric
作爲列數據類型?由於您正在構建字符串,因此我建議將它們存儲爲CHAR來保存投射:
genYear CHAR(2)
CurrentNo INT
CurrentMonth CHAR(2)
將當前否作爲INT,以便於增加。
下面的SP(注意,我沒有測試的代碼,所以可能有一些事情你需要調整)執行以下操作:
1. Sets up variables to hold the 2 digit year and 2 digit month (based on the current date) as CHAR(2).
2. Gets the record for the current year.
3. If there is no record for the current year, it generates the tracking number and inserts a new record (for the current year) into the table
3. If there is a record for the current year, but the month in the table is different than the current month, it generates the tracking number starting at 001. Otherwise, it generates the next tracking number.
3A. It then updates the table.
4. Finally, it returns the tracking number
PROCEDURE [dbo].[generateTrackNo] AS
BEGIN
DECLARE @curYear AS CHAR(2),
@curMonth AS CHAR(2)
DECLARE @dbYear AS CHAR(2),
@dbMonth AS CHAR(2),
@dbNumber AS CHAR(3),
@newNumber AS INT,
@trackingNumber AS CHAR(10)
-- Set up the values for the current year and current moth
SET @curYear = RIGHT(CAST(YEAR(GETDATE()) AS VARCHAR), 2)
SET @curMonth = CAST(MONTH(GETDATE()) AS VARCHAR)
-- Use REPLICATE to pad with a leading 0, if needed
SET @curMonth = REPLICATE('0', 2 - DATALENGTH(@curMonth)) + @curMonth
-- Get the current values from the database for the current year
SELECT @dbYear = genYear,
@dbMonth = currentMonth,
@dbNumber = CAST(CurrentNumber AS VARCHAR)
FROM tblTrackNo
WHERE genYear = @curYear
IF (@dbYear IS NOT NULL)
-- There was a record for the current year
BEGIN
IF (@dbMonth != @currMonth)
-- We're in a new month
BEGIN
SET @newNumber = 2
SET @trackingNumber = 'CAB' + @curYear + @curMonth + '001'
END
ELSE
-- We're in the current month
BEGIN
-- Pad with apprpriate number of leading 0's
SET @dbNumber = REPLICATE('0', 3 - DATALENGTH(@dbNumber) + @dbNumber
SET @trackingNumber = 'CAB' + @curYearChar + @curMonthChar + @dbNumber
SET @newNumber = CAST(@dbNumber AS INT)
END
-- Update the table accordingly
UPDATE tblTrackNo
SET CurrentNo = @newNumber,
CurrentMonth = @curMonth
WHERE genYear = @curYear
END
ELSE
-- We don't have a record in the table for the current year
BEGIN
-- Create the tracking number
SET @trackingNumber = 'CAB' + @curYear + @curMonth + '001'
-- Insert a new record into the table
INSERT INTO tblTrackNo(
genYear,
CurrentNo,
CurrentMonth
)
SELECT @curYear,
2,
@curMonth
END
SELECT @trackingNumber AS trackingNumber
END
這是最有可能不最有效的SP,但它會完成這項工作。您還可能需要考慮將邏輯移出數據庫,並讓應用程序負責根據從表中返回的數據生成跟蹤編號,然後應用程序可以根據需要更新(或插入)。
來源
2011-08-31 06:26:21
Tim
謝謝你,我會嘗試你的代碼.. – breaker