What was your coolest SQL optimization, on a slow performing query?

后端 未结 15 2153
遥遥无期
遥遥无期 2021-02-10 06:45

Just speaking to a colleague of mine. He was walking with a hop in his step, on the way to the coffee machine.

I asked him \"what\'s with the \'swarmy\' walk?\", he said

15条回答
  •  梦谈多话
    2021-02-10 07:33

    One Word, Dynamic Queries

    If you serching with large numbers of parameters you can discount them from the SQL string. This has sped up my queries dramatically and with reletive ease.

    Create PROCEDURE dbo.qryDynamic
    ( 
    
    @txtParameter1 nvarchar(255),
    @txtParameter2 nvarchar(255),
    
    AS
    SELECT     qry_DataFromAView.*
    FROM         qry_DataFromAView
    BEGIN
    
        DECLARE @SQL nvarchar(2500)
        DECLARE @txtJoin nvarchar(50)
    
        Set @txtJoin = ' Where '
    
        SET @SQL = 'SELECT     qry_DataFromAView.*
                    FROM         qry_DataFromAView'
    
        IF @txtParameter1 is not null
        Begin
            SET @SQL=@SQL + @txtJoin + ' Field1 LIKE N''%'' + @dynParameter1 + N''%'') '
            Set @txtJoin = ' And '
        end
    
    
        IF @txtParameter2 is not null
        Begin
            SET @SQL=@SQL + @txtJoin + ' Field2 LIKE N''%'' + @dynParameter2 + N''%'') '
            Set @txtJoin = ' And '
        end
    
        SET @SQL=@SQL + ' ORDER BY Field2'
    
    
        Exec sp_executesql @SQL, N'@dynParameter1 nvarchar(255), @dynParameter2 nvarchar(255)',  @dynParameter1 = @txtParameter1 ,@dynParameter2 = @txtParameter2
    
    END
    GO
    

提交回复
热议问题