2011-03-11 78 views
0

在我的表中,我有一个名为Dep_user_code的列,它只是employeeid ...每当我插入一个新的值时,我需要增加employeeid ..但它有字母和数字..我需要单独增加数字..例如,如果我的雇员是'NECUSER0001'意味着下一次当我插入它必须是'NECUSER0002'动态我不得不产生这样this..everytime当我插入它必须增加值的新雇员..Sql连接问题?

我有尝试像这样的字符串部分和数字部分,但不知道如何实现此...任何建议?

select SUBSTRING(Dep_user_code,1,7) from NEC_Customer_User_Map 
select SUBSTRING(Dep_user_code,8,4) from NEC_Customer_User_Map 

回答

0
declare @max varchar(20) 
declare @number varchar(20) 
select @max = max(cast(substring(dep_user_name , 8, 4) as int)) from NEC_Customer_User_Map (nolock) 
select @max = isnull(@max, 0) + 1 
select @max = (case  when len(@max) = 1 then '000' + @max 
         when len(@max) = 2 then '00' + @max 
         when len(@max) = 3 then '0' + @max 
         else @max 
       end) 
Select @number = (Substring(dep_user_name, 1, PatIndex('%[0-9]%', dep_user_name) - 1) + @max) from NEC_Customer_User_Map      
insert into NEC_Customer_User_Map(Dep_User_Name) values (@number) 
1

你还应该保留一个身份密钥。使用SELECT IDENT_CURRENT('NEC_Customer_User_Map')找出最后插入的ID。

1

如果该值始终文本,然后编号,您裂开使用PATINDEX值:

Select Substring(Dep_user_code, 1, PatIndex('%[0-9]%', Dep_user_code) - 1) As TextPortion 
    , Substring(Dep_user_code, PatIndex('%[0-9]%', Dep_user_code) 
      , Len(Dep_user_code)) As NumberPortion 

但是,是否可以结合使用一个身份与前缀取决于你是否可以允许的差距。如果你不能允许差距,那么你需要查询你可以使用的下一个id值,这可以根据需要以各种方式完成。

1

我已经收到,支持数据库,像这样的设置,虽然我通常不喜欢这种风格的粉丝,我假设你有一些理由不存储在一列中NECUSER和递增的身份整数在PK设置为二者的另一列中。如果没有,我会建议走这条路线,让SQL为你做好工作。

否则,使用以下查询的结果应该会得到您想要的结果。我已添加评论以尝试回答查询可能引发的任何问题。

SELECT SUBSTRING(Dep_user_code, 1, 7) + 
    RIGHT(
     REPLICATE('0', 3) + --Ensure we have padding 0s 
     IsNull(MAX(CAST(SUBSTRING(Dep_user_code, 8, 4) AS INT), -1) + 1 --Work with ints, find MAX or set NULL to -1 so +1 will = 0 
    , 4) --Only want 4 character total from RIGHT function 
FROM NEC_Customer_User_Map 
1
WITH last AS (
    SELECT MAX(Dep_user_code) AS Code 
    FROM NEC_Customer_User_Map 
    WHERE LEFT(Dep_user_code, 7) = 'NECUSER' 
) 
SELECT LEFT(Dep_user_code, 7) + RIGHT(CAST(STUFF(Code, 1, 7, '1') AS int) + 1, 4) 
FROM last 

RIGHT部分执行以下操作:

  • 取代'NECUSER''1'从而获得类似'10002';
  • 将结果转换为int;
  • 增加1;
  • (隐式)将值转换为varchar并获取最后4个字符。

也许STUFF(Code, 1, 7, '1')应该更好地替换为'1' + RIGHT(Code, 4),不确定。

编辑:

... + RIGHT(STUFF(Code, 1, 7, '1') + 1, 4) ... 

... + RIGHT('1' + RIGHT(Code, 4) + 1, 4) ... 
0

您可以考虑:当它发生时,隐式转换也可以在字符串转换为整数太大的情况下使用为了充分利用IDENTITY和IDENT_CURRENT()的几个tsql特性,将Dep_user_code的两个部分作为单独的文件在你的数据库中。