从记录SQL中选择第一个字符串

时间:2014-07-08 15:54:00

标签: sql-server

我有一个查询,到目前为止返回以下内容;

Stock Code  BomReference        Description
2134601A    5134601A         ***DISC*** 004601 EXP Pack I PC Spoo (NF) 500MLX6
2134601A    5109052          40010934 IPC2101 UK PACK  PC SHAMPOO (NF) 500MLX6
2134601A    5134601B         40010908 004601 EXP PACK  PC SHAMPOO 500MLX6
2134601A    5109052L         40010909 IPC2101L UK PACK IPC SPOO  500ML X 6

代码如下;

SELECT     BomComponents.StockCode, BomHeaders.BomReference, BomHeaders.Description
FROM         BomComponents INNER JOIN
                      BomHeaders ON BomComponents.HeaderID = BomHeaders.ID
WHERE StockCode = '2134601A'

我希望能够从描述中选择第一个单词/数字,然后将bom参考和描述组合在一起以产生以下结果。

StockCode        BomReference                                Description
 2134601A        5134601A, 5109052, 5134601B, 5109052L        ***DISC***, 40010934, 40010908, 40010909

任何帮助都会非常有用。

1 个答案:

答案 0 :(得分:1)

创建下面的功能应该为您完成此任务。我经常使用它。

选择dbo.getTokenValue([你的字符串],[分隔字符],[职位])

在这种情况下: 选择dbo.getTokenValue(说明,'', 1

/****** Object:  UserDefinedFunction [dbo].[getTokenValue]    Script Date: 7/8/2014 1:08:08 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


/*
 Accepts the string, delimeter and the position of the required value and returns the value 
*/

create function [dbo].[getTokenValue] (@tokenvalue varchar(200), @Delimeter char, @pos int)
returns varchar(200)
Begin
    Declare @DelimPos int
    Declare @remSubstr varchar(200)
    Declare @FinalStr varchar(200)
    Declare @Count int 
    Declare @Countdelim int

    set @Finalstr = ''
    Set @Countdelim = 0
    Set @remSubstr = @tokenValue
    Set @Count = @pos-1
    set @countdelim = 1

    while @Count <> 0 
        Begin
            Set @DelimPos = charindex(@Delimeter,@remSubstr) 
            If @DelimPos = 0
                Break;
                set @remSubstr = substring(@remSubstr,@DelimPos+1,Len(@remSubstr)-@DelimPos) 
                set @Count = @Count -1
                set @CountDelim = @CountDelim + 1
        End

    If @Pos > @CountDelim
        Begin       
            set @Finalstr = null
            return @FinalStr
        end
    else
        Begin
            Set @DelimPos = charindex(@Delimeter,@remSubstr) 
            if @DelimPos = 0
                Set @Finalstr = @remsubstr
            else 
                Set @FinalStr = substring(@remSubstr,1,@DelimPos-1)
        end

    return @FinalStr
end

GO