2016-06-15 78 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