如何解析sql中两个字符(短划线)之间的中间字符串

时间:2013-08-06 18:13:27

标签: sql sql-server sql-server-2008

我可以解析下面示例的第一部分和最后一部分(sql适用于上一节)。我需要将每个部分解析为它自己的列,但我可能不知道字符串中有多少个破折号。

select right(doc, CHARINDEX('-', reverse(doc))- 1) as Document
from table 

对于Doc值Loan-LDOC-Commercial,它应解析为三列。

对于Doc值Loan-LDOC-COLL-Assignment,它应解析为四列。

2 个答案:

答案 0 :(得分:0)

为此,我使用下表函数。评论包含一个例子:

CREATE FUNCTION dbo.funcSplitToTable
/*
   Split a string into parts base on a separation character to produce
   a table that has one column containing the results of the split.

   EXAMPLE:
      SELECT * FROM dbo.funcSplitToTable( '~', 'MAINT~12221~10001~10/25/2004~CANCELLED~1' )
      SELECT * FROM dbo.funcSplitToTable( '~', '' )
      SELECT * FROM dbo.funcSplitToTable( '~', NULL )
      SELECT * FROM dbo.funcSplitToTable( NULL, 'MAINT~12221~10001~10/25/2004~CANCELLED~1' )
      SELECT * FROM dbo.funcSplitToTable( '', 'MAINT~12221~10001~10/25/2004~CANCELLED~1' )

   RETURN:
      Table with one column containing resulting strings.
*/
(
    @strSearch       AS varchar(255)            -- String to search for.
   ,@strText         AS varchar(MAX )           -- Text to search for string.
)
RETURNS @tblResult TABLE (
    rowid       int NOT NULL identity(1,1),
    result      varchar(MAX) NOT NULL,
    PRIMARY KEY (rowid)
)
AS
BEGIN
    DECLARE @iLastPos        int
          , @iPos            int
          , @lngSearch       int
          , @lngText         int
          , @lngSubstring    int
          , @strResult       varchar(MAX)
          ;
    IF @strText IS NULL RETURN ;
    SET @lngText = LEN(@strText + 'X') - 1 ;

    IF @strSearch IS NULL SET @strSearch = '' ;
    SET @lngSearch = LEN(@strSearch + 'X') - 1 ;

    IF @lngSearch <= 0
    BEGIN
        INSERT INTO @tblResult
        SELECT @strText AS result
        ;
        RETURN ;
    END

    SET @strResult    = NULL ;
    SET @iLastPos     = 1 ;
    SET @iPos         = CHARINDEX( @strSearch, @strText ) ;

    WHILE @iPos > 0
    BEGIN
        SET @lngSubstring = @iPos - @iLastPos ;
        IF @lngSubstring > 0
            INSERT INTO @tblResult
            SELECT SUBSTRING( @strText, @iLastPos, @lngSubstring ) AS result
            ;
        SET @iLastPos  = @iPos + @lngSearch ;
        SET @iPos      = CHARINDEX( @strSearch, @strText, @iLastPos ) ;
    END

    SET @lngSubstring = @lngSearch + @lngText - @iLastPos ;
    IF @lngSubstring > 0
        INSERT INTO @tblResult
        SELECT SUBSTRING( @strText, @iLastPos, @lngSubstring ) AS result
        ;
    RETURN ;
END

答案 1 :(得分:0)

如果你使用过CLR程序,可以使用C#或.NET语言轻松完成,因为它有更好的语法。

string s = "Loan-LDOC-COLL-Assignment";
string []split = s.Split(new char[] {'-'} , StringSplitOptions.None);

Here’s有关如何创建CLR过程并将其添加到数据库的教程。