简体   繁体   中英

SQL Server - Internal error: An expression services limit has been reached

I have a SQL Server stored procedure with nearly 300 variables within it.

The variables were created as follows:

CASE WHEN Grp1 = 'SALES' AND grp_mnth = MONTH_0 THEN SUM(Col)  OVER(PARTITION BY grp_loc,COMM) ELSE 0 END AS "SALES_1"

As this has data issue all the variables were replaced like:

SUM(CASE WHEN Grp1 = 'SALES' AND grp_mnth = MONTH_0 THEN Col ELSE 0 END)  OVER(PARTITION BY grp_loc,COMM) AS "SALES_1"

The data issue has been solved by the above statement, but the procedure throws the below error when we add all the 300 variables, if only about 100 is added, the procedure runs fine.

Internal error: An expression services limit has been reached. Please look for potentially complex expressions in your query, and try to simplify them.

As per the answer posted I have tried to split the query to multiple select queries and the error has been resolved, but while combining the result the data has not been fetched correctly.

BEGIN

CREATE TABLE #TEMPTAB1
(
TYPE_1 char(15),
NUMBER_1 char(7),
STATUS_1 char(1),
...
)
CREATE TABLE #TEMPTAB2
(
TYPE_2 char(15),
NUMBER_2 char(7),
STATUS_2 char(1),
...
)
CREATE TABLE #TEMPTAB3
(
TYPE_3 char(15),
NUMBER_3 char(7),
STATUS_3 char(1),
...
)

SELECT * FROM 
    #TEMPTAB1 T1 
     INNER JOIN 
    #TEMPTAB2 T2 ON T1.TYPE_1=T2.TYPE_2 AND T1.NUMBER_1 = T2.NUMBER_2 AND T1.STATUS_1 = T2.STATUS_2
     INNER JOIN 
    #TEMPTAB3 T3 ON T1.TYPE_1=T3.TYPE_3 AND T1.NUMBER_1 = T3.NUMBER_3 AND T1.STATUS_1 = T3.STATUS_3

END

Can anyone please suggest a way to correct the joins in the above code.

Please re-write your query!

This issue occurs because SQL Server limits the number of identifiers and constants that can be contained in a single expression of a query. This limit is 65,535.

one approach might be :

You can split the select query to multiple select queries.Store the result in temp tables and combine the results at the end.

more info

Fo me it was the SQL Server version. I had no issue with running the same query against SQL Server 2017 on production but was facing the issue with SQL Server 2018 on staging. I downgraded my SQL Server version back to 2017 from 2018 on production and the issue was resolved. This might be an issue with SQL Server 2018 as of now

Right click on your Database, inside database properties, click on options, then change compatibility level to lower one in the list. See this image compatibility level

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM