Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
替换SQL查询中的exist以优化时间_Sql_Sql Server_Performance - Fatal编程技术网

替换SQL查询中的exist以优化时间

替换SQL查询中的exist以优化时间,sql,sql-server,performance,Sql,Sql Server,Performance,我有下面的SQL,它可以在现场工作,但是对于更大的数据集,它已经被证明是超时的 insert into RolePermissions select [ID], R.[ContractManager], @ActionType, null from Roles R where not exists ( select 'x' from RolePerm

我有下面的SQL,它可以在现场工作,但是对于更大的数据集,它已经被证明是超时的

    insert into RolePermissions
    select      
        [ID],
        R.[ContractManager],
        @ActionType,
        null
    from Roles R
    where not exists
    (
        select 'x'
        from RolePermissions
        where [RoleID] = R.[ID]
        and [ActionType] = @ActionType
    );

有人能提出一种优化方法吗?

对于
不存在的
请确保您在
角色权限(RoleID,ActionType)
上有一个索引,您可以将其转换为左外联接,以查看性能优势:

insert into RolePermissions
    select      
        [ID],
        R.[ContractManager],
        @ActionType,
        null
    from Roles R left outer join RolePermissions R on (roleid = R.id)
    WHERE R.ID IS NULL
    AND [ActionType] = @ActionType;

对。首先,您可能希望确保
ActionType
是数字的,因为数字搜索更快。如果有一些文本作为值,则创建一个表来存储操作类型,该表将具有id和文本值,并且在
RolePermissions
中仅存储id引用

接下来,为
RolePermissions
创建一个索引(RoleID,ActionType)

如果仍然很慢,那么创建一个重复执行的任务,加载丢失的记录并插入它们,如果需要,增加超时限制


如果所有操作都失败,则可以在
角色
上创建触发器,从而在
角色权限
中创建所需的记录。暂时关闭对数据库的任何应用程序/访问,暂时增加超时限制,执行您拥有的脚本,恢复为此启用的所有临时操作,从那时起,您将不需要这种类型的插入,因为触发器将确保维护
RolePermissions

表上有哪些索引?你能把索引的定义和你为什么认为可以优化它的查询计划一起发布吗?这不是一个查询。插入零件可能只需要使用时间,而不是选择零件。这将需要更多的IO容量和更大的超时。这就是现实。至少提供一个查询计划。有没有办法对联接执行相同的操作?@UncleDaveIsWatching。添加索引。如果没有正确的索引,
JOIN
s可能对性能没有多大帮助。