ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

  • I am trying to get this script into the @sqlCommand variable. Every time I add something new to it, I have a new battle

    DECLARE @sqlCommand AS nvarchar(1000)

    DECLARE @columnList AS nvarchar(75)= '[Name]'

    DECLARE @tableToSearch AS nvarchar(75) = '[TName]'

    DECLARE @RowCountPerPage INT = 10

    DECLARE @StartingRowNumber INT = 1

    DECLARE @orderBy varchar(20)= '[Name]'

    DECLARE @direction varchar(20) = 'ASC' --'DESC'

    DECLARE @searchTerm varchar(20) = 'Air'

    --SET @sqlCommand = N'

    SELECT DISTINCT [Name] FROM [TNames] WHERE [Name]

    LIKE + '%' + @searchTerm + '%'

    ORDER BY [Name] + ' ' + @direction

    OFFSET @StartingRowNumber

    ROWS FETCH NEXT @RowCountPerPage ROWS ONLY;

  • You can't just build a query on the fly like that.  You need to use dynamic SQL instead.  If you do so and you're accepting user input, be very careful to guard against SQL injection.

    John

  • A better question is what are you attempting to do?

    Because it looks like you are trying to generate T-SQL code based upon a situation.  Like, one proc to run everything.  If so, that's  not usually a great solution.

    Michael L John
    If you assassinate a DBA, would you pull a trigger?
    To properly post on a forum:
    http://www.sqlservercentral.com/articles/61537/

  • SELECT DISTINCT [Name] FROM

    Should not that be Select distinct @columnsList .... etc....?

    I have a feeling you could make use of sp_executeSQL.

    ----------------------------------------------------

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply