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

这足以直接从表中获取第一个 id,但是如果 sql 语句是字符串,我怎样才能得到与上面相同的结果

我的意思是如何获得q.id输出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
4

1 回答 1

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
于 2012-10-14T19:44:04.963 回答