在存储过程中替换“IN”

时间:2013-01-17 05:38:45

标签: sql sql-server sql-server-2008 tsql

我有大量的商店程序。我只粘贴了一小部分。

我的查询:

--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条件{{1}}内的{{1}}。或者建议我一种优化此类查询的替代方法。感谢。

3 个答案:

答案 0 :(得分:1)

由于内部子查询的输出始终相同。你可以把它带到外面并将这些值插入到下面的temptable中,你可以只查询临时表。所以每次它都没有进入循环执行相同的

  `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);

答案 1 :(得分:0)

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

答案 2 :(得分:-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)