gpt4 book ai didi

SQL Server 在 SQL 函数中执行 (sp_executesql ) 命令

转载 作者:行者123 更新时间:2023-12-02 11:38:03 27 4
gpt4 key购买 nike

我在 SQL Server 中创建了一个函数来执行动态 SQL 查询并返回一个值。在 SQL 查询中调用函数时出现错误:

Only functions and some extended stored procedures can be executed from within a function

功能:(返回与@ModuleName关联的用户数量)

DECLARE @Query NVARCHAR(MAX)
DECLARE @Result int
DECLARE @UsersUsingModule AS NVARCHAR(99)

SET @Query = 'SELECT @UsersUsingModule = Count(UR.UserId) '+
'FROM '+@UserDBName+'.[dbo].[aspnet_UsersInRoles] AS UR '+
'INNER JOIN '+@UserDBName+'.[dbo].[aspnet_Roles] AS R ON UR.RoleId = R.RoleId '+
'INNER JOIN '+@UserDBName+'.[dbo].[aspnet_Users] AS U ON UR.UserId = U.UserId '+
'WHERE LOWER(RoleName) IN ( '+
'SELECT LOWER([Role]) '+
'FROM ADMIN_ROLEACCESS '+
'WHERE LOWER(ModuleName) = LOWER(@ModuleName) '+
')'

EXEC sp_executesql @Query, N'@ModuleName nvarchar(max), @UsersUsingModule INT OUTPUT', @ModuleName, @UsersUsingModule OUTPUT

SELECT @Result = CAST(@UsersUsingModule as INT)
RETURN @Result

查询:

SELECT      
M.ID as [ModuleID], M.ModuleName, CC.UserLicenses,
dbo.fncRolesWithModule(M.ModuleName) AS [Roles],
[dbo].[fncUsersUsingModule](M.ModuleName, 'USERS_Demo2016')
FROM
ADMIN_ClientsContracts as CC
INNER JOIN
ADMIN_Modules as M ON CC.ModuleID = M.ID
WHERE
CC.Isactive = 1

如果有更好的方法请告诉我!

最佳答案

函数用于计算,类似于 SELECT 查询。您无法在函数内执行存储过程。在这种情况下,您尝试在函数内使用过程 sp_executesql ,这导致了此问题。

如果您想执行相同的步骤,您可以使用如下过程而不是函数。

CREATE PROCEDURE dbo.GetUserModule
@UserDBName NVARCHAR(50),
@ModuleName NVARCHAR(150)

AS

BEGIN

DECLARE @Query NVARCHAR(MAX)
DECLARE @Result int
DECLARE @UsersUsingModule AS NVARCHAR(99)

SET @Query = 'SELECT @UsersUsingModule = Count(UR.UserId) '+
'FROM '+@UserDBName+'.[dbo].[aspnet_UsersInRoles] AS UR '+
'INNER JOIN '+@UserDBName+'.[dbo].[aspnet_Roles] AS R ON UR.RoleId = R.RoleId '+
'INNER JOIN '+@UserDBName+'.[dbo].[aspnet_Users] AS U ON UR.UserId = U.UserId '+
'WHERE LOWER(RoleName) IN ( '+
'SELECT LOWER([Role]) '+
'FROM ADMIN_ROLEACCESS '+
'WHERE LOWER(ModuleName) = LOWER(@ModuleName) '+
')'

EXEC sp_executesql @Query, N'@ModuleName nvarchar(max), @UsersUsingModule INT OUTPUT'
, @ModuleName
, @UsersUsingModule OUTPUT

SELECT @Result = CAST(@UsersUsingModule as INT)
RETURN @Result

END

关于SQL Server 在 SQL 函数中执行 (sp_executesql ) 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39262640/

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