Question

What is this type of query called (where you build a string to build a kind of temp table and what is its benefits over just using temp tables?

  SET @sqlstring = 'WITH TEMPProc AS
    (
     SELECT
                CustType ,
                [Description] ,
                [ApplyVAT?],
                [ProduceInvoices?] ,
                [PurchaseSale] ,
                TermsDays ,
                DateTimeLastUpdated, 
                ROW_NUMBER() OVER (Order By ' + @SortExpression + ') As RowNumber
        FROM    dbo.CustomerTypes
        )

        SELECT
             CustType ,
                [Description] ,
                [ApplyVAT?],
                [ProduceInvoices?] ,
                [PurchaseSale],
                TermsDays ,
                DateTimeLastUpdated
                FROM TEMPProc
                WHERE
                ROWNUMBER > ' + CONVERT(VARCHAR,@LowerBand) + 
                ' AND ROWNUMBER <' + CONVERT(VARCHAR,@UpperBand)
                + ' ORDER BY ' + @SortExpression

                EXEC sp_executesql @sqlstring
Was it helpful?

Solution

This is dynamic SQL.

It allows you to build a query whose construction relies on information that might not be available at the time you're writing the query. For example, the query might take advantage of parameter values that come out of a table, which weren't there when the query was written.

It makes a query flexible and re-usable, which means that you don't end up writing similar code over and over.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top