1

我有以下在 Sql Server 2008 中运行的查询,如果数据很小,它工作得很好,但是当它很大时,我得到了异常。有什么办法可以优化查询

select
        distinct olu.ID
            from olu_1 (nolock) olu

            join mystat (nolock) s
                on s.stat_int = olu.stat_int

            cross apply
                dbo.GetFeeds 
                        (
                                s.stat_id,
                                olu.cha_int, 
                                olu.odr_int,  
                                olu.odr_line_id, 
                                olu.ID
                        ) channels

            join event_details (nolock) fed
                on fed.air_date = olu.intended_air_date
                and fed.cha_int = channels.cha_int
                and fed.break_code_int = olu.break_code_int

            join formats (nolock) fmt
                on fed.format_int = fmt.format_int


            where
                fed.cha_int in (125, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 35, 36, 37, 38, 39, 40, 41, 43, 117, 45, 42, 44, 47, 49, 50, 51, 46, 52, 53, 54, 55, 56, 48, 59, 60, 57, 63, 58, 62, 64, 66, 69, 68, 67, 65, 70, 73, 71, 74, 72, 75, 76, 77, 78, 79, 82, 80, 159, 160, 161, 81, 83, 84, 85, 88, 87, 86, 89, 90, 61, 91, 92, 93, 95, 96, 97, 98, 99, 100, 94, 155, 156, 157, 158, 103, 104, 102, 101, 105, 106, 107, 108, 109, 110, 119, 111, 167, 168, 169, 112, 113, 114, 115, 116, 170, 118, 120, 121, 122, 123, 127, 162, 163, 164, 165, 166, 128, 129, 130, 124, 133, 131, 132, 126, 134, 136, 135, 137, 171, 138, 172, 173, 174) and
                fed.air_date between '5/27/2013 12:00:00 AM' and '6/2/2013 12:00:00 AM' and

                fmt.cha_int in (125, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 35, 36, 37, 38, 39, 40, 41, 43, 117, 45, 42, 44, 47, 49, 50, 51, 46, 52, 53, 54, 55, 56, 48, 59, 60, 57, 63, 58, 62, 64, 66, 69, 68, 67, 65, 70, 73, 71, 74, 72, 75, 76, 77, 78, 79, 82, 80, 159, 160, 161, 81, 83, 84, 85, 88, 87, 86, 89, 90, 61, 91, 92, 93, 95, 96, 97, 98, 99, 100, 94, 155, 156, 157, 158, 103, 104, 102, 101, 105, 106, 107, 108, 109, 110, 119, 111, 167, 168, 169, 112, 113, 114, 115, 116, 170, 118, 120, 121, 122, 123, 127, 162, 163, 164, 165, 166, 128, 129, 130, 124, 133, 131, 132, 126, 134, 136, 135, 137, 171, 138, 172, 173, 174) and
                fmt.air_date between '5/27/2013 12:00:00 AM' and '6/2/2013 12:00:00 AM' 
4

2 回答 2

1

IN (Transact-SQL)

在 IN 子句中包含大量值(数千个)会消耗资源并返回错误 8623 或 8632。要解决此问题,请将 IN 列表中的项目存储在表中。

因此,我建议将值插入临时表,然后加入该表或从表中选择 IN

所以像

DECLARE @TABLE TABLE(
        val INT
)

INSERT INTO @TABLE VALUES(1),(2),(3),(4),(5)

SELECT  *
FROM    MyTable
WHERE   ID IN (SELECT val FROM @TABLE)

SQL 小提琴演示

于 2013-05-30T07:39:39.060 回答
0

从您的生产数据库(有很多行)进行备份,并在您的开发机器上本地使用它。优化可能需要一些时间,如果您是 sql 新手,实际上可能会非常困难。将查询分解为几个临时表,最后将它们连接在一起。尝试从 Query 中删除 dbo.GetFeeds(...) 函数,以查看该函数是否存在问题。

于 2013-05-30T07:48:34.487 回答