格式化序列

时间:2015-08-17 15:24:03

标签: sql sql-server sql-server-2008

我需要创建一个格式化为VT-000/2015的SQL Server序列, 其中零是从每年的记录增加的账单号,从2015年的同一年开始 e.g:

VT-001/2014,
VT-002/2014,
VT-003/2014,
VT-004/2014,
VT-001/2015,
VT-002/2015

我该怎么做?

3 个答案:

答案 0 :(得分:0)

考虑你的表是这样的:

CREATE TABLE PRODUCT ([SERIAL] NVARCHAR(30), [YEAR] INT, [COUNTER] INT)

以下是您可以使用的程序:

CREATE PROCEDURE PRODUCT_INSERT
@YEAR INT
AS 
BEGIN
    DECLARE @COUNTER INT
    SELECT @COUNTER = ISNULL(MAX([COUNTER]), 0) + 1 FROM PRODUCT
    WHERE [YEAR] = @YEAR
    INSERT INTO PRODUCT
    VALUES ('VT-' + REPLACE(STR(@COUNTER, 3), SPACE(1), '0') + '/' + CONVERT(nvarchar(4),@YEAR), @YEAR, @COUNTER)
END

答案 1 :(得分:0)

实现表格中的行号是有问题的。我认为一个观点是这项工作的正确工具。

以下是通过创建视图并使用ROW_NUMBER()

来实现此目的的一种方法
CREATE TABLE PRODUCT (PRODUCT_ID int,YEAR INT);

CREATE VIEW dbo.VIEW_PRODUCT AS
SELECT 
      PRODUCT_ID,
      [YEAR], 
      ROW_NUMBER() OVER(PARTITION BY [YEAR] ORDER by [YEAR]) AS RowNum,
      'VT-' + RIGHT(replicate('0', 3) 
       + cast(ROW_NUMBER() OVER(PARTITION BY [YEAR] ORDER by [YEAR]) AS VARCHAR(10)), 3) 
       + '/' + cast(YEAR AS VARCHAR(4)) as SERIAL
FROM PRODUCT;

INSERT INTO PRODUCT VALUES
(1000,2014),
(2000,2014),
(3000,2015),
(4000,2015),
(5000,2015);

SQL Fiddle Demo

答案 2 :(得分:0)

如果您使用的是SQL Server 2012,则可以使用序列和计算列 - 如下所示:

第1步:定义序列

act2

您可以在新的一年的1月1日将该序列重置为1,以便在新的一年中从1开始获取新的数字

第2步:定义你的表,包括一个计算列,它将各个部分连接在一起:

CREATE SEQUENCE dbo.YearlyNumbers
   START WITH 1
   INCREMENT BY 1 ;
GO

现在,当您在表中插入值时:

CREATE TABLE dbo.Product 
(
    ProductID INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
    ProductDate DATE,
    -- default constraint gets a new value from the sequence on every insert
    SequenceValue INT
       CONSTRAINT DF_Product_SeqValue DEFAULT(NEXT VALUE FOR YearlyNumbers),
    -- computed column puts together all bits to create the formatted ID you're looking for   
    FormattedID AS 'VT-' + RIGHT('0000' + CAST(SequenceValue AS VARCHAR(4)), 4) + 
                   '/' + CAST(YEAR(ProductDate) AS VARCHAR(4)) PERSISTED
)

INSERT INTO dbo.Product (ProductDate) VALUES ('20150115'), ('20150331'), ('20150222'), ('20150414'), ('20150526') 将从序列中获取值,计算列显示所请求的格式化ID:

INSERT

enter image description here