如何在没有param定义的情况下创建动态查询?

时间:2014-09-23 11:27:01

标签: sql sql-server

我需要通过加入他们的post_id来找到来自tbl_post表(created_date)的前10个帖子以及来自tbl_post_track的热门帖子。如果热门帖子在top10之后排在top_id那么我需要将帖子的数量添加到前10名以完成10次

有没有方法可以在没有param声明的情况下计算以下查询?因为我在每张表中都有大量数据,所以请帮助我。

declare @mainselectsql  varchar(4000)= ''
declare @resultsql      varchar(4000)= ''
declare @countsql      nvarchar(4000)
declare @parm          nvarchar(50)  = '@max_count int output'      
declare @totalcount    int

/* This is my Main Query */
Set @mainselectsql = 'select *,case when [count] is not null and  New_post <= 10 then 1 else 0 end as Total from
                          (
                           select row_number() over(order by p.created_date desc) as [New_post],p.post_id,title,p.created_date,[count]
                           from  tbl_post p with (nolock)
                           left outer join (select top 4 post_id,count(post_id)[count]from tbl_post_track with (nolock) group by post_id order by count(post_id) desc) z
                           on z.post_id = p.post_id
                           ) x'

SET @CountSQL = ' SELECT @max_Count = sum(Total)FROM ('+ @mainselectsql +')t'

/* I need to calculate count no of top_4_posts (outer join) has come under top_10_latest posts */

execute sp_executesql @CountSQL, @parm, @max_Count = @totalcount output;

/* Now I need to add the count to result set to display top_10 posts */
set @resultsql  = 'select *,case when [count] is not null then ''Popular'' when New_post <= 10+'+conv**strong text**ert(varchar,@totalcount)+' then ''New'' else null end as Status
                        from    (' + @mainselectsql + ')t
                        where  1=1'
exec   (@resultsql)

谢谢!

0 个答案:

没有答案