如何在SQL中以字母开头增加我的id [英] How to increment my id filed starting with a alphabet in SQL

查看:229
本文介绍了如何在SQL中以字母开头增加我的id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的表中有一个标识字段OrderNo在nvarchar中订购数据类型

我有orderNo 20000,T20000

如何使用MAX函数自动增量我需要20001或T20001



我尝试过:



选择'T'+ CONVERT(VARCHAR(10),max(OrderNo)+1)AS OrderNo来自tblOrderMaster 

解决方案

如果你想要在你的数据库中使用前面的'T'来保存OrderNumber,那么你将需要一个单独的列来存储它(这就是为什么你得到你的我得到这样的错误转换nvarchar值时转换失败' T20001'到数据类型int错误)。



您已经声明 OrderNo 是一个身份字段,所以没有必要使用MAX() - 实际上你应该从不使用它作为生成唯一id的方法(不能保证它在多用户数据库中是唯一的) 。



要使用前面的T获取订单号,只需使用

 选择 '  T' + CAST(OrderNo  AS   VARCHAR  AS  OrderNoWithPrefix 来自 tblOrderMaster 

说实话,没有必要在数据库上保留这个值,因为它似乎只是一个显示功能 - 只需在需要时添加T.


检查出来:向您的数据库询问该唯一ID [ ^ ]


 选择 '  T' +  CONVERT  VARCHAR ,MAX(OrderNo)+1,< span class =code-digit> 103 ) AS  OrderNo 来自 tblOrderMaster 


I have a identity filed OrderNo in my table Orders the datatype in nvarchar
I have the orderNo 20000, T20000
How to autoincrement with MAX function i need 20001 or T20001

What I have tried:

select 'T' + CONVERT(VARCHAR(10),max(OrderNo)+1)AS OrderNo  from tblOrderMaster

解决方案

If you want to persist the OrderNumber with the 'T' preceding it in your database then you will need a separate column to store it in (this is why you are getting your "I am getting error like this "Conversion failed when converting the nvarchar value 'T20001' to data type int" error).

You have already stated that OrderNo is an Identity field so there is no need to use MAX() - in fact you should never use that as a method for generating a "unique" id (there is no guarantee it will be unique in a multi-user database).

To get your order number with the preceding "T" just use

select 'T' + CAST(OrderNo AS VARCHAR) AS OrderNoWithPrefix from tblOrderMaster

To be honest there is no need to persist this value on the database as it appears to be a display only feature - just add the T when you need it.


Check this out: Ask Your Database for that Unique ID[^]


select 'T' + CONVERT(VARCHAR, MAX(OrderNo)+1, 103) AS OrderNo from tblOrderMaster


这篇关于如何在SQL中以字母开头增加我的id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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