Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql query with function that return 2 values

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

like image 887
John Avatar asked Dec 03 '22 05:12

John


1 Answers

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
like image 93
vmvadivel Avatar answered Dec 21 '22 22:12

vmvadivel