将字符串拆分器tvf w / cte转换为过滤的缩放器功能

时间:2016-05-05 16:50:19

标签: sql sql-server

我需要拆分30,000个地址。这是我可以与其他几个相似大小的列表进行某些特定匹配。我发现代码效果很好,但需要获取特定的单个字段而不是返回的表。

从这段代码:

CREATE FUNCTION dbo.Split (@sep char(1), @s varchar(512))
RETURNS table
AS
RETURN (
    WITH Pieces(pn, start, stop) AS (
      SELECT 1, 1, CHARINDEX(@sep, @s)
      UNION ALL
      SELECT pn + 1, stop + 1, CHARINDEX(@sep, @s, stop + 1)
      FROM Pieces
      WHERE stop > 0
    )
    SELECT pn,
      SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS s
    FROM Pieces
  )

经过多次尝试,我结束了修改后的代码:

USE [AddrTools]
GO

/****** Object:  UserDefinedFunction [dbo].[fnGetPart]    Script Date: 5/4/2016 1:23:33 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

create function [dbo].[fnGetAddrPart]
(
@sep as char(1),
@iPart as int,
@sFullAddr as varchar(200),
@iPartCnt as int
)
returns varchar(30)
as
Begin

declare @sPart as varchar(30)

set @sep = ' '

;
with Pieces(pn, start, stop) AS 
(
      SELECT 1, 1, CHARINDEX(@sep, @sFullAddr)
      UNION ALL
      SELECT pn + 1, stop + 1, CHARINDEX(@sep, @sFullAddr, stop + 1)
      FROM Pieces
      WHERE stop > 0
    )
set @sPart =
(
SELECT 
    SUBSTRING(@sFullAddr, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS s
    FROM Pieces
    where pn = @iPart
)
return(@sPart)
end

GO

我收到了这个错误:

  

Msg 444,Level 16,State 2,Procedure fnGetAddrPart,Line 27   函数中包含的Select语句不能将数据返回给客户端。

此外,第一个带红色下划线的代码上的悬停错误位于set @spart的集合上。

  

语法不正确需要设置'

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

我认为最后一个查询的正确语法更像是这样:

SELECT @sPart =
    SUBSTRING(@sFullAddr, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS s
    FROM Pieces
    where pn = @iPart

那应该超过Msg 444错误。