如何迭代SQL结果值中的字符?

时间:2015-11-23 19:10:50

标签: sql sql-server-2012

我们有一个包含ID和标题的工作表,如下所示:

JobID | JobTitle
1       president
2       vice-president
3       director

用户表包含一个应该映射到作业表的jobID,但是编码它的人使其成为UI中的多选字段,并在其间添加管道。因此,用户可以是总裁,副总裁和董事。以下是用户表的示例

UserName | JobID
Suzy       1|2|3
Bob        3
Jane       2|1

我正在尝试运行所有员工及其职位的报告,但我对如何遍历多值jobID并显示jobTitle感到困惑。

我目前使用的查询类似于:

select user.username, job.JobTitle 
from user 
inner join job on user.JobID = job.JobID

这完全在SQL Server 2012上

有什么建议吗? 我决心在后续行或后续列中显示其他标题,无论更容易。

1 个答案:

答案 0 :(得分:1)

这是一个可用于拆分分隔字段并将结果返回到表格的函数(您可以在后续操作中使用):

CREATE FUNCTION dbo.ufnGENSplitDelimField (
    @InputString nvarchar(max),
    @Delimiter nvarchar(10)
)

RETURNS @Results TABLE (
    Item nvarchar(50)
)
AS
BEGIN

-- default delimiter to comma if blank
IF ISNULL(@Delimiter,'') = ''
BEGIN
    SET @Delimiter = ','
END

DECLARE @Item nvarchar(50);
DECLARE @ItemList nvarchar(max);
DECLARE @DelimIndex int;

SET @ItemList = @InputString
SET @DelimIndex = CHARINDEX(@Delimiter, @ItemList, 0)

/*
Loop through all items, removing the first at each iteration.  For example, if we start with the string 'bob,mary,joe':
    1. set @Item = 'bob'
    2. insert 'bob' into result table
    3. set @ItemList = 'mary,joe'
    4. set @DelimIndex = 4
    loop
*/
WHILE (@DelimIndex != 0)
BEGIN
    SET @Item = SUBSTRING(@ItemList, 0, @DelimIndex)
    INSERT INTO @Results VALUES (@Item)

    -- Set @ItemList = @ItemList minus one less item
    SET @ItemList = SUBSTRING(@ItemList, @DelimIndex+1, LEN(@ItemList)-@DelimIndex)
    SET @DelimIndex = CHARINDEX(@Delimiter, @ItemList, 0)
END -- End WHILE

IF @Item IS NOT NULL -- At least one delimiter was encountered in @InputString, and we need to insert the final item in the list
BEGIN
    SET @Item = @ItemList
    INSERT INTO @Results VALUES (@Item)
END
ELSE -- No delimiters were encountered in @InputString, so just return @InputString
BEGIN
    INSERT INTO @Results VALUES (@InputString)
END

RETURN;
END;