2013-05-12 72 views
0

我遇到問題:我試圖完全更新SQL Server 2012中的臨時表(在存儲過程中),但它只更新與我的描述相匹配的第一個條目。下面是代碼:完全更新臨時表SQL

create table #t (store_name varchar(30), 
       product_name varchar(30), 
       price int, 
       valab_since date, 
       valab_until date, 
       best_offer varchar(3)) 

--some code that populates my table 

update #t set best_offer = 'yes' 
where price = (select min(price) from Cataloage as c 
       INNER JOIN Produse as p 
       on c.codP = p.codP 
       where p.denumire = #t.store_name) 
update #t set best_offer = 'no' 
where price > (select min(price) from Cataloage as c 
       INNER JOIN Produse as p 
       on c.codP = p.codP 
       where p.denumire = #t.product_name) 

select * from #t 

CataloageProduse是一些表,我使用。

回答

0

要覆蓋所有記錄,首先將它們全部設置爲「否」,然後運行單獨的查詢,以便用商店的最低價格更新那些記錄。

update #t set best_offer = 'no'; 

;with t as (
    select *, rnk = dense_rank() over (partition by t.store_name order by price asc) 
    from Cataloage c 
    join Produse p on c.codP = p.codP 
    join #t t on p.denumire = t.store_name 
) 
update t 
set best_offer = 'yes' 
where rnk = 1; 

我已經使用了DENSE_RANK和一個公用表表達式來替代您的逐行子查詢。

+0

感謝您的及時回覆。我不得不做一些小的修改,但基本上它做到了。 – 2013-05-13 20:20:17