我有一个表值函数,如下所示:
ALTER FUNCTION [dbo].[SplitStr]
(@sep char(1), @s nvarchar(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
)
我现在尝试从另一个脚本中调用它:
declare @referencestring varchar(512)
declare @s varchar(512)
set @s = 'cow is running|-reference_temp|horse is jumping';
set @referencestring = (select ss.val
from (select dbo.SplitStr(@s, '|') as val) ss
where ss.val like '%-reference%');
但这样做会给我带来错误:
找不到任何一列" dbo"或用户定义的函数或聚合" dbo.SplitStr",或名称不明确。
我想要做的就是从split函数返回的表有三行,我只想把包含字符串-reference
的行作为字符串。它应该存储在referencestring
变量中。
答案 0 :(得分:-1)
基于Aarons链接,这有效:
CREATE FUNCTION dbo.SplitStrings_Moden
(
@List NVARCHAR(MAX),
@Delimiter NVARCHAR(255)
)
RETURNS TABLE
WITH SCHEMABINDING AS
RETURN
WITH E1(N) AS ( SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1),
E2(N) AS (SELECT 1 FROM E1 a, E1 b),
E4(N) AS (SELECT 1 FROM E2 a, E2 b),
E42(N) AS (SELECT 1 FROM E4 a, E2 b),
cteTally(N) AS (SELECT 0 UNION ALL SELECT TOP (DATALENGTH(ISNULL(@List,1)))
ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E42),
cteStart(N1) AS (SELECT t.N+1 FROM cteTally t
WHERE (SUBSTRING(@List,t.N,1) = @Delimiter OR t.N = 0))
SELECT Item = SUBSTRING(@List, s.N1, ISNULL(NULLIF(CHARINDEX(@Delimiter,@List,s.N1),0)-s.N1,8000))
FROM cteStart s;
go
declare @referencestring varchar(512)
declare @s varchar(512)
set @s = 'cow is running|-reference_temp|horse is jumping';
set @referencestring = (select item from dbo.SplitStrings_Moden(@s, '|')
where item like '%-reference%');
print @referencestring