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
答案 0 :(得分: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