gpt4 book ai didi

带有返回 2 个值的函数的 Sql 查询

转载 作者:行者123 更新时间:2023-12-02 05:34:17 25 4
gpt4 key购买 nike

我将如何从查询中 SQL Server 中的用户定义函数返回多个值(例如,一个数字和一个字符串)?

例如 select col1, dbo.function1(col2) from table
结果是

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

我不想调用该函数 2 次,因为我使用了一些复杂的代码并且我不想执行它两次。只是为了在 Return 中取最后 2 个结果

最佳答案

摘自 - 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,'jeff@jeff.com' UNION ALL
SELECT 2,'yak@sqlteam.com' UNION ALL
SELECT 3,'billg@microsoft.com'

--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

关于带有返回 2 个值的函数的 Sql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8903441/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com