2014-07-08 72 views
0

我有一個查詢到目前爲止返回以下;從記錄中選擇第一個字符串SQL

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 

任何幫助將是巨大的幫助。

+0

請參閱http://stackoverflow.com/questions/273238/how-to-use-group-by-to-concatenate-strings-in-sql-server –

+0

而要獲取描述的第一個單詞,請參閱http:/ /stackoverflow.com/questions/707610/extract-the-first-word-of-a-string-in-a-sql-server-query –

回答

1

創建下面的函數應該爲你做到這一點。我經常使用它。

選擇dbo.getTokenValue([你的字符串],[定界符],[位置])

在這種情況下: 選擇dbo.getTokenValue(描述, ',)

/****** 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)[email protected]) 
       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 
相關問題