sql server 设计的varchar字段是否能自增长

发布时间:2024-05-15 10:20 发布:上海旅游网

问题描述:

比如我设计一个表
create table users
(
userid varchar(50) primary key
)
第一次自动插入数据S00001,第二次为S00002
可以的话麻烦给写个例子谢谢了

问题解答:

sql本身不支持 需要另外的表和存储过程来实现
1 表:

create table LastestNo
(
No int
)
2 存储过程:
create proc GetFormatNo
(
@FormatPre varchar(50),
@FormatNo varchar(50) output
)
as
Begin
declare @Count int
select @Count=Count(*) from LastestNo
if(@Count=0)
Insert into LastestNo values(1)
select @FormatNo=@FormatPre+convert(varchar(10),No) from LastestNo
print @formatNo
update lastestNo set No=No+1
End

测试:
declare @out varchar(40)
exec GetFormatNo 'aaa',@FormatNo=@out out
select @out
输出依次为 aaa1,aaa2,aaa3,aaa4

可以!
实现方式是能过表的 Insert 触发器!

具体细节楼主可以研究一下Insert 触发器的内容或与我联系。

:若硬盘空间允许的话,可将字段宽度:【加宽】最大范围100等,自动增长(理想化了),不现实。目前实现有难度。

自己做触发器来实现 或者用 NEWID() 也不会重复

热点新闻