从逗号分隔的值中获取名称

时间:2014-11-26 09:33:21

标签: sql sql-server sql-server-2008 tsql sql-server-2012

我有两个SQL Server表,EmployeeMstEmployeeHistory

EmployeeMst是我的主表,EmployeeHistory是我的记录表。

我在EmployeeHistory

中存储以逗号分隔的值

现在我希望使用T-SQL查询来获取员工姓名

我的表EmployeeMst

EmpNo   EmpName
---------------------
1       abc
2       xyz
3       apple
4       banan
5       apk
6       ico
7       exe
8       botle
9       dev
10      tbl
11      col
12      fun
13      dbo
14      xnb
15      png
16      jpgn
17      pngns
18      dknd
19      dnckd
20      dnicnd

EmployeeHistory

EmpYear    EmpNo
---------------------------------
2010       1,2,3,10,11,12,13
2011       1,2,3,4,5,6,16,17,18

现在我想要输出如下

输出:

EmpYear  EmpNo   EmpName
2010      1       abc
2010      2       xyz
2010      3       apple
2010      10      tbl
2010      11      col
2010      12      fun
2010      13      dbo
2011      1       abc
2011      2       xyz
2011      3       apple
2011      4       banan
2011      5       apk
2011      6       ico
2011      16      jpgn
2011      17      pngns
2011      18      dknd

EmpNo column

中有很多以逗号分隔的值

SQLFIDDLE

1 个答案:

答案 0 :(得分:0)

试试这段代码:

 CREATE FUNCTION [dbo].[SplitString]  
( 
    -- Add the parameters for the function here 
    @myString nvarchar(max), 
    @deliminator nvarchar(10) 
) 
RETURNS  
@ReturnTable TABLE  
( 
    -- Add the column definitions for the TABLE variable here 
    [part] [nvarchar](max) NULL 
) 
AS 
BEGIN 
        Declare @iSpaces int 
        Declare @part nvarchar(max) 

        --initialize spaces 
        Select @iSpaces = charindex(@deliminator,@myString,0) 
        While @iSpaces > 0 

        Begin 
            Select @part = substring(@myString,0,charindex(@deliminator,@myString,0)) 

            Insert Into @ReturnTable(part) 
            Select @part 

    Select @myString = substring(@mystring,charindex(@deliminator,@myString,0)+ len(@deliminator),len(@myString) - charindex(' ',@myString,0)) 


            Select @iSpaces = charindex(@deliminator,@myString,0) 
        end 

        If len(@myString) > 0 
            Insert Into @ReturnTable 
            Select @myString 

    RETURN  
END

然后

select part from  SplitString('a,b,c,d,e,f,g',',')