4

How would I return multiple values (say, a number and a string) from a user-defined function in SQL Server inside a query?

e.g select col1, dbo.function1(col2) from table

and the result to be

Col1 |        Col2       |         Col3
-----+-------------------+---------------------
x    | Num from function | String from function

I don't want to call the function 2 times because i use some complex code and i don't want to execute it twice. Just to take the final 2 results in the Return

3 Answers 3

14

Extract from - http://www.sqlteam.com/article/returning-complex-data-from-user-defined-functions-with-cross-apply

Returning multiple values from a UDF can be done fairly easily in SQL Server, but we must return those values as a virtual table

--Sample Table
CREATE TABLE emails 
(
    ID INT PRIMARY KEY, 
    EmailAddress VARCHAR(100)
)
GO

--Dummy Data
INSERT INTO emails
SELECT 1,'[email protected]' UNION ALL
SELECT 2,'[email protected]' UNION ALL
SELECT 3,'[email protected]'

--UDF Creation
CREATE FUNCTION EmailParse (@email VARCHAR(1000))
RETURNS @t TABLE (UserName VARCHAR(20), Domain VARCHAR(20))
AS
BEGIN
    DECLARE @i INT

    SELECT @i = charindex('@', @email,1);

    IF (@i > 1)
        INSERT INTO @t VALUES (LEFT(@email,@i-1), SUBSTRING(@email,@i+1,20))
    ELSE
        INSERT INTO @t VALUES (NULL,NULL)

    RETURN 
END


--UDF Usage
SELECT 
    emails.ID, s.Username, s.Domain
FROM 
    emails
CROSS APPLY 
EmailParse(emails.EmailAddress) s
Sign up to request clarification or add additional context in comments.

Comments

5

I would probably create a table UDF. Something along the lines of this:

CREATE FUNCTION [owner].[function_name]
(
      @parm1 <datatpe> = <default>
)
RETURNS TABLE
AS
      RETURN
      (
      SELECT <column1, column2, ...>
      FROM <table, view, etc.>
      WHERE <some condition applies>      -- optional clauses
)

more info here.

It might seem like kind of a waste if you are only returning one row, but I think your alternatives(xml, parsing values from string on the fly) would make things much harder .

2 Comments

Thanks for your reply. What about if i want to return 2 declared variables?
@John Is there something wrong with RETURN (SELECT @Var1, @Var2)?
0

You can't create a function that returns two values. What's the problem when you call the function twice?

i have found an article in TechNet which explains how to create a Table-Valued User-Defined Functions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.