管道在SQL中以内联方式进行内联

时间:2016-01-18 15:54:36

标签: sql sql-server

您好我在执行查询时跟踪数据

enter image description here

我也有管道分离Colum ReportType的功能,但它正在写我的列

我希望得到以下格式的结果

ItemID |ReportType|EmailAddrress |FirstName|LastName
1      |        1  |abc@gmail.com| test    |test 
1      |        2  |abc@gmail.com| test1   |test1

我的SQL函数似乎毫无用处

我的功能是

ALTER FUNCTION [dbo].[fnSplit](
    @sInputList VARCHAR(8000) -- List of delimited items
  , @sDelimiter VARCHAR(8000) = '|' -- delimiter that separates items
) RETURNS @List TABLE (item VARCHAR(8000))

BEGIN
DECLARE @sItem VARCHAR(8000)
WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
 BEGIN
 SELECT
  @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,@sInputList,0)-1))),
  @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))

 IF LEN(@sItem) > 0
  INSERT INTO @List SELECT @sItem
 END

IF LEN(@sInputList) > 0
 INSERT INTO @List SELECT @sInputList -- Put the last item in
RETURN
END

选择是正常查询

SELECT ItemId,ReportType,EmailAddress,FirstName,LastName
来自EmailInfo

1 个答案:

答案 0 :(得分:1)

如果我理解你的问题,那么我认为这就是你想要实现的目标。

SELECT ItemId, col.item AS ReportType, EmailAddress, FirstName, LastName
FROM EmailInfo
CROSS APPLY dbo.fnSplit(ReportType, '|') col