2013-04-26 40 views
-1

我想讓自動編號在SQL Server這樣如何用相結合,使自動編號在SQL Server年月

BK/201304 /技術

BK:只要Inisialisation
2013:是一年
04:月
0002:是increament,然後再返回要是下個月是改變

感謝

+2

只是好奇,你爲什麼要這樣做? – 2013-04-26 01:31:15

+0

什麼是Inisialisation? – Paparazzi 2013-04-26 01:34:09

+0

我這樣做是爲了在vb.net中創建應用程序,而BK就是表單的名稱vb.net – user2322009 2013-04-26 01:39:19

回答

1

下面的解決方案假定您已經有一個序列表。序號或號碼錶只是一個帶有遞增號碼的(一列)表。

select 'BK/' 
    + cast(year(getdate()) as varchar) 
    + right('00' + cast(month(getdate()) as varchar), 2) 
    + '/' 
    + right('0000' + cast(isnull((select max(Seq) + 1 from SequenceTable), 0) as varchar), 4) 

請讓我知道,如果你還沒有一個。我會更新我的答案,包括一個給你。

UPDATE - 包含在SequenceTable中的代碼。

create table SequenceTable 
(
    Seq int not null identity(1, 1) 
) 

create proc dbo.IncrementSeq 
as 
set nocount on 

if day(getdate()) = 1 
    truncate table SequenceTable -- Reset 
else 
    insert SequenceTable default values -- Increment 

return 0 
go 

我開始做了很多假設,這讓我很不舒服。上面的代碼假設您可以在生成自動序列號之前調用存儲過程。如果是這樣,您甚至可以將所有代碼作爲一個步驟包含在存儲過程中。見下面的代碼:

create proc dbo.IncrementSeq 
as 
set nocount on 

if day(getdate()) = 1 
    truncate table SequenceTable -- Reset 
else 
    insert SequenceTable default values -- Increment 

select 'BK/' 
    + cast(year(getdate()) as varchar) 
    + right('00' + cast(month(getdate()) as varchar), 2) 
    + '/' 
    + right('0000' + cast(isnull((select max(Seq) + 1 from SequenceTable), 0) as varchar), 4) 

return 0 
go 

更新 - 我已經改進了我的答案的完整性和簡單性。

create table SequenceTable 
(
    Seq varchar(max) not null 
) 

insert SequenceTable 
select 'BK/' 
    + cast(year(Getdate()) as varchar) 
    + right('00' + cast(month(getdate()) as varchar), 2) 
    + '/' 
    + case when day(getdate()) = 1 then '0000' 
     else right('0000' + cast(isnull((select right(max(Seq), 4) + 1 from SequenceTable), 0) as varchar), 4) 
    end 
+0

我沒有序列表 – user2322009 2013-04-26 01:51:27

+0

我沒有一個表自動編號增量,因爲如果有增量字段,他仍然會計數刪除被刪除。 即時使用SQL Server 2005 – user2322009 2013-04-26 01:57:26

+0

那麼你需要創建一個,或者你不認爲它會解決你的問題? – 2013-04-26 02:12:42

相關問題