Search code examples
sql-server-2008query-timeout

SQL Server query times out


I have created a SQL query that runs on SQL Server 2008. For some reason it takes a long time and times out incomplete.

This is my query modified for test purposes. The column FileData is a varbinary(max) and the primary key is ContentFileId. As you can see I am only trying to select a single specific record.

SELECT *,
       CASE
         WHEN [CMS_tbContentFile].[FileData] IS NULL 
         THEN (
                SELECT [CMS_tbContentFile2].[FileData]
                FROM   [CMS_tbContentFile] AS [CMS_tbContentFile2]
                WHERE  [CMS_tbContentFile2].[ContentFileId] = 2152  
              )
         ELSE [CMS_tbContentFile].[FileData]
       END AS [Test]
FROM   [CMS_tbContentFile]
WHERE  [CMS_tbContentFile].[ContentFileId] = 3054  

The subquery in the CASE (SELECT [CMS_tbContentFile2].[FileData] FROM [CMS_tbContentFile] AS [CMS_tbContentFile2] WHERE [CMS_tbContentFile2].[ContentFileId] = 2152) runs fine on its own, and if I remove that part of the main query the main query runs fine. It is only the combination of the CASE and the subquery that causes the problem.

Hopefully by looking at the above someone will see the issue, possibly some problem with this type of query that is not possible in T-SQL?


Solution

  • You are not giving us much info but anyway: The subselect runs for every row, so when you have a 1000 fields where [CMS_tbContentFile].[ContentFileId] = 3054 then it can/will execute 1000 times.

    Try the code below or try to rewrite it an a join.

    declare @field varchar(255) //define here the same type as the [filedata] column has
    select 
       @field = [cms_tbcontentfile2].[filedata] 
    from 
       [cms_tbcontentfile] as [cms_tbcontentfile2]
    where 
       [cms_tbcontentfile2].[contentfileid] = 2152
    
    SELECT 
       *, 
       isnull([CMS_tbContentFile].[FileData], @field) as [Test]
    FROM 
       [CMS_tbContentFile] 
    WHERE 
       [CMS_tbContentFile].[ContentFileId] = 3054