将扩展存储过程添加到 SQL Server

适用于:SQL Server

重要

在 SQL Server的未来版本中将删除此功能。 请避免在新的开发工作中使用该功能,并着手修改当前还在使用该功能的应用程序。 请改用 CLR 集成。

包含扩展存储过程函数的 DLL 充当 SQL Server 的扩展。 若要安装 DLL,请将该文件复制到目录,例如包含标准 SQL Server DLL 文件(C:\Program Files\Microsoft SQL Server\MSSQL12.0)。默认情况下,x\MSSQL\Binn。

将扩展存储过程 DLL 复制到服务器后,SQL Server 系统管理员必须将每个扩展存储过程函数注册到 DLL 中的每个扩展存储过程函数。 可以使用 sp_addextendedproc 系统存储过程完成该操作。

重要

在将扩展存储过程添加到服务器并将执行权限授予其他用户之前,系统管理员应当对它进行彻底检查,确保它不包含有害或恶意的代码。 验证所有用户的输入。 验证之前,不要串联用户输入。 绝对不要执行根据尚未验证的用户输入构造的命令。

sp_addextendedproc 的第一个参数指定函数的名称,第二个参数指定包含该函数的 DLL 的名称。 建议指定 DLL 的完整路径。

重要

升级到 SQL Server 2005 或更高版本后,未使用完整路径注册的现有 DLL 将无法工作。 若要更正该问题,请使用 sp_dropextendedproc 撤消注册 DLL,然后使用 sp_addextendedproc 注册,并指定完整路径。

sp_addextendedproc 中指定的函数名称必须与 DLL 中的函数名称完全相同,包括大小写。 例如,此命令将位于名为 xp_hello.dll 的 dll 中的函数xp_hello,注册为 SQL Server 扩展存储过程:

sp_addextendedproc 'xp_hello', 'c:\Program Files\Microsoft SQL Server\MSSQL13.0.MSSQLSERVER\MSSQL\Binn\xp_hello.dll';  

如果指定的 sp_addextendedproc 函数名称与 DLL 中的函数名称不完全匹配,则新名称将在 SQL Server 中注册,但该名称将不可用。 例如,虽然 xp_Hello 注册为位于的 xp_hello.dllSQL Server 扩展存储过程,但如果稍后用于 xp_Hello 调用该函数,SQL Server 将无法在 DLL 中找到该函数。

--Register the function (xp_hello) with an initial upper case  
sp_addextendedproc 'xp_Hello', 'c:\xp_hello.dll';  
  
--Use the newly registered name to call the function  
DECLARE @txt varchar(33);  
EXEC xp_Hello @txt OUTPUT;  
  
--This is the error message  
Server: Msg 17750, Level 16, State 1, Procedure xp_Hello, Line 1  
Could not load the DLL xp_hello.dll, or one of the DLLs it references. Reason: 127(The specified procedure could not be found.).  

如果指定 sp_addextendedproc 函数的名称与 DLL 中的函数名称完全匹配,并且 SQL Server 实例的排序规则不区分大小写,则用户可以使用名称中小写字母和大写字母的任意组合调用扩展存储过程。

--Register the function (xp_hello)  
sp_addextendedproc 'xp_hello', 'c:\xp_hello.dll';  
  
--The following will succeed in calling xp_hello  
DECLARE @txt varchar(33);  
EXEC xp_Hello @txt OUTPUT;  
  
DECLARE @txt varchar(33);  
EXEC xp_HelLO @txt OUTPUT;  
  
DECLARE @txt varchar(33);  
EXEC xp_HELLO @txt OUTPUT;  

当 SQL Server 实例的排序规则区分大小写时,SQL Server 将无法调用扩展存储过程(即使它注册的名称和排序规则与 DLL 中的函数完全相同),如果过程以不同的大小写调用。

--Register the function (xp_hello)  
sp_addextendedproc 'xp_hello', 'c:\xp_hello.dll';  
  
--The following will result in an error  
DECLARE @txt varchar(33);  
EXEC xp_HELLO @txt OUTPUT;  
  
--This is the error  
Server: Msg 2812, Level 16, State 62, Line 1  

不需要停止和重启 SQL Server。

另请参阅

sp_addextendedproc (Transact-SQL)
sp_dropextendedproc (Transact-SQL)