Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I call a function which returns a table and accepts a varchar?

I have a function I need to use, I'm passing in a var char and I insert records into a table called using @ValueList. However I'm not sure how to call / use this function ?

ALTER FUNCTION [dbo].[GetListFromCSVString]
(            
      @csvString varchar(500)
)
RETURNS @ValueList TABLE 
(
      ListValue varchar(50)
)
AS
begin
      -- body

End
like image 537
Jules Avatar asked Aug 30 '11 08:08

Jules


People also ask

Which of the functions return a table?

The RETURNS TABLE specifies that the function will return a table. As you can see, there is no BEGIN... END statement. The statement simply queries data from the production.

How do you call a table-valued function in SQL?

The simple definition of the table-valued function (TVF) can be made such like that; a user-defined function that returns a table data type and also it can accept parameters. TVFs can be used after the FROM clause in the SELECT statements so that we can use them just like a table in the queries.

What is table-valued function?

A table function, also called a table-valued function (TVF), is a user-defined function that returns a table. You can use a table function anywhere that you can use a table. Table functions behave similarly to views, but a table function can take parameters.


1 Answers

select ListValue
from dbo.GetListFromCSVString('1,2,3')

Result:

ListValue
----------
1
2
3

If the parameter to your function is a field in another table you have to use cross apply get the list of values for each row in the source table.

-- Table to test on
declare @T table
(
  ID int identity primary key, 
  SomeColumn varchar(500)
)

-- Sample data
insert into @T values('1,2,3')
insert into @T values('a,b,c')

-- Use the function
select ST.ID,
       GL.ListValue
from @T as ST
  cross apply dbo.GetListFromCSVString(ST.SomeColumn) as GL

Result:

ID          ListValue
----------- ----------
1           1
1           2
1           3
2           a
2           b
2           c
like image 156
Mikael Eriksson Avatar answered Oct 18 '22 10:10

Mikael Eriksson