• SQL SERVER 如何处理带字母的自增列--【叶子】


    1. --需求说明:  
    2. /*  
    3. id         col  
    4. ---------- ----------  
    5. AB00001    a  
    6. AB00002    b  
    7. --当再插入数据的时候让id自动变成AB00003  
    8. */  
    9.   
    10. --1.求最大值法(高并发时不适用,只是介绍个思路)  
    11. --测试数据  
    12.   
    13. if object_id('[macotb]'is not null   
    14. drop table [macotb]  
    15. create table [macotb] (id varchar(7),col varchar(1))  
    16. insert into [macotb]  
    17. select 'AB00001','a' union all  
    18. select 'AB00002','b'  
    19.   
    20. declare @max varchar(7)  
    21. select @max='AB'+right('00000'+ltrim(max(replace(id,'AB','')+1)),5) from [macotb]  
    22. insert into [macotb] select @max,'c'  
    23.   
    24. select * from [macotb]  
    25. /*  
    26. id      col  
    27. ------- ----  
    28. AB00001 a  
    29. AB00002 b  
    30. AB00003 c  
    31. */  
    32.   
    33. --2.利用@@identity,分步处理  
    34. if object_id('[macotb]'is not null   
    35. drop table [macotb]  
    36.   
    37. create table [macotb] ([noint identity,id varchar(7),col varchar(1))  
    38. insert into [macotb]  
    39. select 'AB00001','a' union all  
    40. select 'AB00002','b'  
    41.   
    42. insert into [macotb](col) select 'c'  
    43. update [macotb]   
    44. set id='AB'+right('00000'+ltrim([no]),5) where [no]=@@identity  
    45.   
    46. select id,col from [macotb]  
    47. /*  
    48. id      col  
    49. ------- ----  
    50. AB00001 a  
    51. AB00002 b  
    52. AB00003 c  
    53. */  
    54.   
    55. --3.直接添加运算列  
    56. if object_id('[macotb]'is not null   
    57. drop table [macotb]  
    58.   
    59. create table [macotb]   
    60. (  
    61.     [noint identity,  
    62.     id as ('AB'+right('00000'+ltrim([no]),5)),  
    63.     col varchar(1)  
    64. )  
    65.   
    66. insert into [macotb](col) select 'a' union all select 'b'  
    67.   
    68. select id,col from [macotb]  
    69. /*  
    70. id           col  
    71. ------------ ----  
    72. AB00001      a  
    73. AB00002      b  
    74. */  
    75.   
    76. insert into [macotb](col) select 'c' union all select 'd'  
    77. select id,col from [macotb]  
    78. /*  
    79. id           col  
    80. ------------ ----  
    81. AB00001      a  
    82. AB00002      b  
    83. AB00003      c  
    84. AB00004      d  
    85. */  
    86.   
    87. --叶子建议使用第三种方式!  
  • 相关阅读:
    springloud系列搭建注册中心
    在生产环境下禁用swagger
    consul怎么在windows下安装
    linux上传与下载
    使用git将本地代码提交到码云上去
    springboot整合activemq(三)配置文件
    springboot整合activemq(二),消费均匀分析
    Python3学习之路~3.2 递归、函数式编程、高阶函数、匿名函数、嵌套函数
    Python3学习之路~3.1 函数基本语法及特性、返回值、参数、局部与全局变量
    Python3学习之路~2.9 字符编码与转码
  • 原文地址:https://www.cnblogs.com/douqiumiao/p/3365313.html
Copyright © 2020-2023  润新知