如何在表格列中自动生成特定值?我想在"WD-2010-0001","WD-2010-0002", "WD-2010-0003"
之类的列中自动生成值,依此类推。任何人都可以帮忙??
先谢谢
答案 0 :(得分: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
等等。
答案 1 :(得分: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
答案 2 :(得分: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))
答案 3 :(得分: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
答案 4 :(得分: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