0
SET ROWCOUNT @startRowIndex
     SELECT @first_id = id FROM Question q ORDER BY q.id

this is straight forward enough to get the first id from a table, however in case the sql statement is in string, how can i get the same result like above

i mean how to get output q.id from EXEC sp_executesql @sql?

IF  @sortCommand like 'sortAsAnswerCount' OR 
    @sortCommand like 'sortAsNonAnswer'
BEGIN

    set @sql=N'WITH LikeCounts
        AS
        (
        SELECT     TOP (100) PERCENT q.Id, q.Title, c.CustomerId, c.CreatedOnUtc,
                                  (SELECT     COUNT(*)
                                    FROM          dbo.CustomerLikeQuestion
                                    WHERE      (QuestionId = q.Id)) AS LikeCount
        FROM         dbo.CustomerContent AS c INNER JOIN
                              dbo.Question AS q ON c.Id = q.Id
        ORDER BY likecount DESC
        )
        SELECT *, row_number() over (order by likecount desc) as RowNum
        fROM LikeCounts'

END
Cristian Lupascu
  • 39,078
  • 16
  • 100
  • 137
nam vo
  • 3,271
  • 12
  • 49
  • 76

1 Answers1

0
declare @params nvarchar(max), @sql nvarchar(max), @first_id int

select @params = "@first_id int output"

IF  @sortCommand like 'sortAsAnswerCount' OR 
    @sortCommand like 'sortAsNonAnswer'
BEGIN

    set @sql=N'WITH LikeCounts
    AS
    (
    SELECT     TOP (100) PERCENT q.Id, q.Title, c.CustomerId, c.CreatedOnUtc,
                              (SELECT     COUNT(*)
                                FROM          dbo.CustomerLikeQuestion
                                WHERE      (QuestionId = q.Id)) AS LikeCount
    FROM         dbo.CustomerContent AS c INNER JOIN
                          dbo.Question AS q ON c.Id = q.Id
    ORDER BY likecount DESC
    )
    SELECT @first_id = id
    fROM LikeCounts'

END

exec dbo.sp_executesql
    @stmt = @sql,
    @params = @params,
    @first_id = @first_id output
Roman Pekar
  • 107,110
  • 28
  • 195
  • 197