搜索两个字符串之间的公共前缀

时间:2015-01-28 11:12:46

标签: sql-server string compare

我有一个存储过程:

ALTER PROCEDURE [dbo].[traxs_Paybook_Data_Validate]

    @session_id varchar(30)
    @paybook_start_number varchar(30)
    @paybook_end_number varchar(30)

AS

    UPDATE traxs_temp..__PaybookImport SET
        /* BEGIN CHANGE */
        prefix = null,
        start_number = CAST(@paybook_start_number AS int),
        end_number = CAST(@paybook_end_number AS int)
        /* END CHANGE */
    WHERE   
        session_id = @session_id

价值观如下:

@paybook_start_number = 100

@paybook_end_number = 200

现在,支票簿号码可以有一个前缀,即:

@paybook_start_number = ABC100

@paybook_end_number = ABC200

前缀并不总是相同,也不是它的长度。我需要找到前缀(如果有),将其存储到prefix中并在投票前将其从付款簿号码中删除。

由于

2 个答案:

答案 0 :(得分:2)

试试这个:

DECLARE @z VARCHAR(32) = 'ukasd10';
SELECT LEFT(@z, PATINDEX('%[0-9]%', @z) - 1) AS Prefix,REPLACE(SUBSTRING(@z, PATINDEX('%[0-9]%', @z), LEN(@z)), ',', '') AS Digits

同样使用此逻辑更新列前缀.... 感谢

答案 1 :(得分:1)

您需要一个函数从输入字符串中提取数字/数值,以及一个从输入字符串中提取字母的函数。

提取数字的功能

CREATE FUNCTION dbo.fn_Extract_Numbers
(
  @string NVARCHAR(100)
)
RETURNS INT 
AS
BEGIN 
    DECLARE @int_Value INT;


SELECT @int_Value = LEFT(subsrt, PATINDEX('%[^0-9]%', subsrt + 't') - 1) 
FROM (
    SELECT subsrt = SUBSTRING(@string, pos, LEN(@string))
    FROM (
           SELECT @string AS string , PATINDEX('%[0-9]%', @string) AS Pos
         ) d
     ) t

  RETURN @int_Value;
END

提取字母的功能

CREATE FUNCTION dbo.fn_Extract_Alphabets
(
  @string NVARCHAR(100)
)
RETURNS NVARCHAR(100) 
AS
BEGIN 
    DECLARE @Alpha_Value NVARCHAR(100);


SELECT @Alpha_Value = LEFT(subsrt, PATINDEX('%[^a-z]%', subsrt + 't') - 1) 
FROM (
    SELECT subsrt = SUBSTRING(@string, pos, LEN(@string))
    FROM (
           SELECT @string AS string , PATINDEX('%[a-z]%', @string) AS Pos
         ) d
     ) t

  RETURN @Alpha_Value;
END

现在,在存储过程中使用这些函数来提取Alphabet / Prefix位和Number位,并将它们存储在目标列中。

像......那样的东西。

ALTER PROCEDURE [dbo].[traxs_Paybook_Data_Validate]

    @session_id varchar(30)
    @paybook_start_number varchar(30)
    @paybook_end_number varchar(30)

AS
  DECLARE @Start_Num_Prefix VARCHAR(100);
  DECLARE @End_Num_Prefix   VARCHAR(100);
  DECLARE @Start_Num_Numbers INT;
  DECLARE @End_Num_Numbers   INT;

SELECT  @Start_Num_Prefix   = dbo.fn_Extract_Alphabets(@paybook_start_number)
SELECT  @End_Num_Prefix     = dbo.fn_Extract_Alphabets(@paybook_end_number)
SELECT  @Start_Num_Numbers  = dbo.fn_Extract_Numbers(@paybook_start_number)
SELECT  @End_Num_Numbers    = dbo.fn_Extract_Numbers(@paybook_end_number)


..... rest of your procedure and so on....