Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Special Customized Incremental Column in SQL Server 2012

Suppose I have a table TableTask with 3 columns:

TaskID, DesignID, TaskName

I would like to have TaskName a special column which its auto number depending on DesignID, and I would like to have repeated .XXX portions but each record is still unique because there is IDX portion

ID1.001, ID1.002, ..., ID1.999
ID2.001, ID2.002

I have tried something like what I have in the code below but I can only get

ID1.001, ID1.002, ID1.003, ID2.004, ID2.005

My code:

CREATE TABLE TableTask
(
    TaskID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
    DesignID INT NOT NULL,
    TaskName AS 'ID' + CAST(DesignID AS VARCHAR(6)) + '.' +
                       RIGHT('000' + CAST(TaskID AS VARCHAR(3)), 3) PERSISTED
)
like image 620
Secret Avatar asked Aug 13 '26 10:08

Secret


1 Answers

You could do that at query time with row_number (example with variable for easy testing):

declare @TableTask TABLE 
(
    TaskID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
    DesignID INT NOT NULL
)

insert into @TableTask values(1), (2), (1), (1), (2), (3), (4)

select *, 
    'ID' + CAST(DesignID AS VARCHAR(6)) + '.' + RIGHT('000' + convert(varchar(3), row_number() over (partition by DesignID order by TaskID)), 3) AS TasName
from @TableTask

Output:

1   1   ID1.001
3   1   ID1.002
4   1   ID1.003
2   2   ID2.001
5   2   ID2.002
6   3   ID3.001
7   4   ID4.001
like image 121
Pedro Lorentz Avatar answered Aug 16 '26 18:08

Pedro Lorentz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!