2

如何在表的列中自动生成特定值?我想在诸如此类的列中自动生成值"WD-2010-0001","WD-2010-0002", "WD-2010-0003"。谁能帮忙??

提前致谢

4

5 回答 5

1

正如我在评论中所说,我会分别存储不同的部分,然后使用计算列对其进行格式化。这可能很简单:

create table T (
    _ID int IDENTITY(20100001,1) not null,
    ID as 'WD-' + LEFT(CONVERT(varchar(10),_ID),4) + '-' + SUBSTRING(CONVERT(varchar(10),_ID),5,10),
    ColumnA int not null
)
go
insert into T(ColumnA) values (10)
go
select ID,ColumnA from T

产生:

ID                 ColumnA
------------------ -----------
WD-2010-0001       10

下一个插入将是WD-2010-0002, 等等。

于 2013-08-12T07:39:11.353 回答
1

在计算列中使用表达式

IF OBJECT_ID('dbo.test2') IS NOT NULL DROP TABLE dbo.test2
CREATE TABLE dbo.test2
 (
  Id int IDENTITY,
  colLikeWd varchar(2) DEFAULT 'WD',
  colLikeYear varchar(4) DEFAULT '2010',
  colLikeAuto AS colLikeWd + '-' + colLikeYear + '-' + RIGHT('0000' + CAST(Id AS varchar(4)), 4),
  colAnother varchar(100)
  )
GO 

INSERT dbo.test2(colAnother)
VALUES('AnotherColumn')
GO 5  

SELECT *
FROM dbo.test2

见演示SQLFiddle

于 2013-08-12T07:39:25.843 回答
0

这可能会帮助你

DECLARE @String varchar(20)='WD-2010-0001'

SELECT 'WD-2010-'+
        REPLICATE('0', 4 - LEN(REVERSE(CAST(REVERSE(LEFT(REVERSE(@String),
                  CHARINDEX('-', REVERSE(@String)) -1)) AS INT)+1 )))+ 
       CAST(CAST(REVERSE(left(REVERSE(@String), CHARINDEX('-', 
               REVERSE(@String)) -1)) AS INT)+1 AS VARCHAR(4))

替换@String 为您的column name

于 2013-08-12T07:28:24.653 回答
0

我认为 OP 的意思不是如何生成特定的值,而是如何自动填充列。我认为使用触发器是正确的方法。就像是:

CREATE TRIGGER [Add_WD] on dbo.MyTable AFTER INSERT AS
UPDATE dbo.MyTable
SET WD = '' -- you can put your value generation logic here.
FROM Inserted i
WHERE dbo.MyTable.PrimaryId = i.PrimaryId
于 2013-08-12T07:16:32.207 回答
0

很难说出你真正想做的事情,但可能是这样的

select
    'WD-20' + 
    right('00' + cast(cast(rand() * 15 as int) + 1 as nvarchar(2)), 2) + '-' +
    '000' + cast(cast(rand() * 9 as int) + 1 as nvarchar(1))
于 2013-08-12T07:00:53.457 回答