2016-06-15 77 views
-3

我有这条线我的查询:SQL update语句顶部和底部行

UPDATE Tnm_Lookup SET 
P_C = 'C' 
    where Tnm_Lookup_ID in (select top (355) Tnm_Lookup_ID 
    from Tnm_Lookup 
    where Tnm_Lookup_ID = Tnm_Lookup_ID 
    order by Tnm_Lookup_ID DESC); 

GO 

我也有一个对目前试图修复它的顶部行。 基本上我需要一些指导,我可以如何通过不是非常具体的即选择顶部(355)来实现我的结果?

根据谁在使用它,此表格的大小可能不同,因此它可以或多或少地启动,并且可以更新。

+0

那么,你想更新表的第一行和最后一行吗?你的问题有点不清楚 – Marusyk

+0

就是你问的问题:如何为TOP谓词传递一个变量rowcount? – dlatikay

+0

使用%而不是355? – xQbert

回答

0

如果将查询封装在存储过程中,则可以传入rowcount的参数,例如, @RowCount,然后用@RowCount替换355。

+0

这可能工作。让我试试这个。抱歉,我更多的是前端开发人员,然后是后端。 – user2516641

0

是的,我问的是说我有一个表有950行,一半的表是原始数据,另一个是被复制的。我不需要使用一定数量的行,而需要使用另一种适用于较小和较大表格的方法。

+0

你应该编辑你的问题来澄清它,而不是隐藏一个伪装成答案的评论。 – HABO

0

这样的事情?

declare @t table (id int, trim_lookup_id int,p_c varchar(1)) 

insert into @t values 
(1,1, null), 
(20,2, null), 
(2,3, null), 
(26,4, null), 
(50,5, null), 
(51,1, null), 
(51,2, null), 
(53,3, null), 
(54,4, null), 
(55,5, null) 

;with cte as 
(
    select id,trim_lookup_id,p_c,row_number() over(partition by trim_lookup_id order by id) rn 
from @t 
) 
update @t 
    set p_c = 'C' 
from @t t 
join cte on cte.id = t.id 
where cte.rn = 2 

select * from @t