ID Name
GL001 一
GHK01 二
MN_OP 三
GL002 四
GL003 五
GL004 六
GHK02 七
GHK03 八
MLKPO 九
L_PO09 十
GL005 十一
我新添加一条数据的时候,我想取出所有ID以:'GL'开头的数据,并且获得当前‘GL’的最大值(上面的例子为:005)而新添加的这条数据就是:GL006了,请问如何实现?
select 'GL' + CAST( SUBSTRING(以'GL'开头且最大的一个),2,3) + 1 as nvchar(20))
3 个解决方案
#1
select cast('GL' + right('00'+rtrim(SUBSTRING(max(id),2,3) + 1),3) as nvarchar(20))
from temp
where id like 'GL%'
from temp
where id like 'GL%'
#2
如果你的字符串长度固定就没问题,不然问题多多
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-11-15 11:01:44
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
-- Dec 28 2012 20:23:12
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[TempTable]
if object_id('[TempTable]') is not null drop table [TempTable]
go
create table [TempTable]([ID] varchar(6),[Name] varchar(4))
insert [TempTable]
select 'GL001','一' union all
select 'GHK01','二' union all
select 'MN_OP','三' union all
select 'GL002','四' union all
select 'GL003','五' union all
select 'GL004','六' union all
select 'GHK02','七' union all
select 'GHK03','八' union all
select 'MLKPO','九' union all
select 'L_PO09','十' union all
select 'GL005','十一'
--------------开始查询--------------------------
select cast('GL' + right('00'+rtrim(SUBSTRING(max(id),3,3) + 1),3) as nvarchar(20))
from [TempTable]
where id like 'GL%'
----------------结果----------------------------
/*
--------------------
GL006
*/
#3
谢谢,非常感谢大家~~
#1
select cast('GL' + right('00'+rtrim(SUBSTRING(max(id),2,3) + 1),3) as nvarchar(20))
from temp
where id like 'GL%'
from temp
where id like 'GL%'
#2
如果你的字符串长度固定就没问题,不然问题多多
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-11-15 11:01:44
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
-- Dec 28 2012 20:23:12
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[TempTable]
if object_id('[TempTable]') is not null drop table [TempTable]
go
create table [TempTable]([ID] varchar(6),[Name] varchar(4))
insert [TempTable]
select 'GL001','一' union all
select 'GHK01','二' union all
select 'MN_OP','三' union all
select 'GL002','四' union all
select 'GL003','五' union all
select 'GL004','六' union all
select 'GHK02','七' union all
select 'GHK03','八' union all
select 'MLKPO','九' union all
select 'L_PO09','十' union all
select 'GL005','十一'
--------------开始查询--------------------------
select cast('GL' + right('00'+rtrim(SUBSTRING(max(id),3,3) + 1),3) as nvarchar(20))
from [TempTable]
where id like 'GL%'
----------------结果----------------------------
/*
--------------------
GL006
*/
#3
谢谢,非常感谢大家~~