0

I am getting the following error :

Msg 208, Level 16, State 6, fnToken Procedure, Line 24
Invalid object name 'dbo.fnToken'.

I tried returning all the numbers ..

select dbo.fnToken('#254#251451#')
ALTER FUNCTION dbo.fnToken
(   
@Token varchar(100)
)
RETURNS @Listenum TABLE(num varchar(50))
AS
begin
declare @compt int
declare @num varchar(50)
set @compt = 1
while  SUBSTRING(@token,@compt,1)<>''
    begin
        if SUBSTRING(@Token,@compt+1,@compt)<>'#'
            begin
                set @num= @num+SUBSTRING(@Token,@compt+1,1)
                set @compt=@compt+1
            end
        else 
            begin
                Insert  into @Listenum(num) values(@num)
                
            end 
    end 
Return (SELECT num FROM @Listenum)

ENd 

This is the expected output :

254

251451

Community
  • 1
  • 1

3 Answers3

1

You can try:

SELECT  value
  FROM  STRING_SPLIT('#254#251451#', '#')
 WHERE  TRIM(value) <> '';

Depending on your version of SQL-Server its a built in function. If your on an older version have a look at string split functions on here. There are plenty of options.

Matthew Baker
  • 2,637
  • 4
  • 24
  • 49
0

You can't reference a Table-Value Function like a Scalar Function. But this is a really bad way of splitting values out of a delimited value as it's iterative. Use an XML Splitter, DelimitedSplit8K_LEAD or STRING_SPLIT (if you're on SQL Server 2016+).

If you're using STRING_SPLIT the correct syntax would be:

SELECT SS.[value] AS num
FROM STRING_SPLIT(''#254#251451#','#') SS
WHERE SS.[value] != '';

The same syntax would be true for DelimitedSplit8K_LEAD, if you're not on SQL Server 2016+.

Edit: Op is using an old (and about to be completely unsupported) version of SQL Server, so they will need to use DelimitedSplit8k.

Thom A
  • 88,727
  • 11
  • 45
  • 75
0

Here is a solution. Hope to help, my friend :))

I added more @separator param, you can remove it by fixing "#" value.

ALTER FUNCTION dbo.fnToken
(   
@stringToSplit VARCHAR(MAX), @separator nchar(1)
)
RETURNS @Listenum TABLE(num varchar(50))
AS
begin
DECLARE @name NVARCHAR(255)
 DECLARE @pos INT

 WHILE CHARINDEX(@separator, @stringToSplit) > 0
 BEGIN
  SELECT @pos  = CHARINDEX(@separator, @stringToSplit)  
  SELECT @name = SUBSTRING(@stringToSplit, 1, @pos-1)

  INSERT INTO @Listenum 
  SELECT @name

  SELECT @stringToSplit = SUBSTRING(@stringToSplit, @pos+1, LEN(@stringToSplit)-@pos)
 END

 INSERT INTO @Listenum
 SELECT @stringToSplit
Return

ENd 


SELECT num 
FROM dbo.fnToken('#254#251451#', '#')
WHERE TRIM(num) <>''
Tomato32
  • 2,145
  • 1
  • 10
  • 10