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 に答える