简体   繁体   English

SQL用户定义函数

[英]SQL User Defined Functions

I am currently working with User Defined Functions and having a hard time grasping the concept around how the function accepts one parameter and returns another one. 我目前正在使用用户定义函数,并且很难理解有关函数如何接受一个参数并返回另一个参数的概念。

I have a table that has Employee ID and Log IDs. 我有一个包含员工ID和日志ID的表。 The UDF should accepts the EmployeeID and returns UserLoginID. UDF应该接受EmployeeID并返回UserLoginID。 The UserLoginID is the last part of the LogID column after the '\\'. UserLoginID是'\\'之后的LogID列的最后一部分。 I need to return the entire column from the table. 我需要从表中返回整列。

Table Example 表例

EmployeeID   LoginId
1    database\userid1
2    database\userid2
3    database\userid3

UDF query 1: UDF查询1:

CREATE FUNCTION dbo.fx_IDtest]
(@EmployeeID int)

RETURNS nvarchar(50)
AS
BEGIN
DECLARE @UserID nvarchar(50)
SET @UserID = (SELECT SUBSTRING(LoginID,CHARINDEX('\',LoginID)+1, LEN(LoginID)) 
            FROM HumanResources.Employee
            WHERE EmployeeID = @EmployeeID
            )
RETURN @UserID
END

UDF query 2: UDF查询2:

CREATE FUNCTION [dbo].[fx_IDtest2] 
(@EmployeeID int)

RETURNS table
AS
RETURN
(SELECT SUBSTRING(LoginID,CHARINDEX('\',LoginID)+1, LEN(LoginID)) as USERID
            FROM HumanResources.Employee
            WHERE EmployeeID = @EmployeeID
            )

FYI... Your first function is fine, and does exactly what I believe you want... I think perhaps you're not calling the function correctly. 仅供参考...您的第一个函数很好,并且完全符合我认为的要求...我认为您可能没有正确调用该函数。

I tested it as follows... 我测试如下

/*
CREATE TABLE testDATA (EmployeeID int, LoginID nvarchar(50))

insert into testDATA
select 1,    'database\userid1' union
select 2,    'database\userid2' union
select 3,    'database\userid3'

CREATE FUNCTION dbo.fx_IDtest
(@EmployeeID int)

RETURNS nvarchar(50)
AS
BEGIN
DECLARE @UserID nvarchar(50)
SET @UserID = (SELECT SUBSTRING(LoginID,CHARINDEX('\',LoginID)+1, LEN(LoginID)) 
            FROM testDATA
            WHERE EmployeeID = @EmployeeID
            )
RETURN @UserID
END
*/

SELECT *, dbo.fx_IDtest(EmployeeID)
FROM testDATA
WHERE EmployeeID = 1

SELECT dbo.fx_IDtest(1)

Both select statements, give me userid1 as a return. 这两个select语句都给我userid1作为回报。

Notice, that you must provide the schema for UDF's in your SELECT , this is often overlooked. 注意,您必须在SELECT提供UDF的模式,这通常被忽略。 You cannot do SELECT fx_IDtest(1) instead you must do SELECT dbo.fx_IDtest(1) 您不能执行SELECT fx_IDtest(1)而必须执行SELECT dbo.fx_IDtest(1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM