如何更改自动生成的ID列的格式 [英] How to change the format of a auto generated ID column

查看:78
本文介绍了如何更改自动生成的ID列的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



有谁能告诉我如何在Sql server中更改自动生成的ID列的格式为

如果ID为1我想让它成为001 ,

2到002 ..所以。

但我想在Select Query中想要这个,而不为这种格式创建任何列。



任何帮助将不胜感激。在此先感谢Smile | :)



谢谢

Hi,
Can anyone tell me How to change the format of a auto generated ID column in Sql server as
if ID is 1 i want to make it 001,
2 to 002 ..so on.
but i want this in Select Query without creating any column for this format.

Any help will be appreciated. Thanks in advance Smile | :)

Thanks

推荐答案

嗨Saroj,



试试这个,



Hi Saroj,

Try this,

CREATE TABLE test1
(ID INT IDENTITY,Val CHAR(2))

INSERT into test1 VALUES('AA'),('BB'),('CC'),('EE'),('FF'),('GG'),('HH'),('II'),('JJ'),('KK'),('LL'),('MM')

select case when LEN(ID)<=2 then right(('000'+convert(varchar,ID)),3) else convert(varchar,ID) end as ID,Val
from Test1





结果:



Result :

ID	Val
001	AA
002	BB
003	CC
004	EE
005	FF
006	GG
007	HH
008	II
009	JJ
010	KK
011	LL
012	MM





希望它有帮助...:)



Hope it helps... :)


这可以帮助



May this helps

CREATE TABLE Increment
(ID INT IDENTITY,Val CHAR(2))
INSERT Increment VALUES('AB'),('CD'),('EF')

SELECT REPLACE(STR(Id,3),' ',0)[Id],Val FROM Increment







Id	Val
001	AB
002	CD
003	EF


请参阅以下链接获取类似文章:

使用SQL Server自定义自动生成的序列 [ ^ ]

SQL Server中自动生成的序列号 [ ^ ]




- Amit
Refer the links below for similar articles:
Custom Auto-Generated Sequences with SQL Server[^]
Auto generated sequence number in SQL Server[^]


--Amit


这篇关于如何更改自动生成的ID列的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆