0

我有巨大的存储过程。我只粘贴其中的一小部分。

我的查询:

--declare variable and Select Statement goes here
WHERE  ((v.[RoleID] IN (
         SELECT [dbo].[aspnet_UsersInRoles].roleid 
         FROM [dbo].[aspnet_UsersInRoles] 
         INNER JOIN [dbo].[aspnet_Users] 
           ON [dbo].[aspnet_Users].userid = [dbo].[aspnet_UsersInRoles].userid 
         WHERE 
           [dbo].[aspnet_Users].username = @UserName 
         UNION ALL 
         SELECT [RoleId] 
         FROM   dbo.aspnet_roles 
         WHERE loweredrolename = 'anonymous user') 
OR v.username = @UserName)) 

查询工作完美,但需要很长时间才能执行。条件里面有这么多WHERE条件IN我认为里面的子查询IN需要时间。有没有办法优化这个查询并替换IN内部WHERE条件。或者建议我另一种方法来优化这种类型的查询。谢谢。

4

3 回答 3

1

由于内部子查询的输出始终相同。您可以将其取出并将这些值插入到如下所示的临时表中,然后您可以查询临时表。所以每次它不会进入循环执行相同的

  `create table #temp(roleid int); `

  ` insert into #temp as (sSELECT [dbo].[aspnet_UsersInRoles].roleid 
     FROM [dbo].[aspnet_UsersInRoles] 
     INNER JOIN [dbo].[aspnet_Users] 
       ON [dbo].[aspnet_Users].userid = [dbo].[aspnet_UsersInRoles].userid 
     WHERE 
       [dbo].[aspnet_Users].username = @UserName 
     UNION ALL 
     SELECT [RoleId] 
     FROM   dbo.aspnet_roles 
     WHERE loweredrolename = 'anonymous user');`

    WHERE  ((v.[RoleID] IN ( select roleid from #temp);
于 2013-01-17T06:04:33.593 回答
0

您可以使用 IN 子句的结果创建一个临时表并加入它。这会将问题分解为两个更简单的任务。

于 2013-01-17T05:44:44.877 回答
-2

根据 Orangecrush 的建议

--declare variable and Select Statement goes here
WHERE  EXISTS (
         SELECT 1
         FROM [dbo].[aspnet_UsersInRoles] 
         INNER JOIN [dbo].[aspnet_Users] 
           ON [dbo].[aspnet_Users].userid = [dbo].[aspnet_UsersInRoles].userid 
         WHERE 
           [dbo].[aspnet_Users].username = @UserName 
             AND [dbo].[aspnet_UsersInRoles].roleid = v.[RoleID]
         UNION ALL 
         SELECT 1
         FROM   dbo.aspnet_roles 
         WHERE loweredrolename = 'anonymous user'
           AND dbo.aspnet_roles.roleid = v.[RoleID])
OR v.username = @UserName)
于 2013-01-17T07:56:46.547 回答