Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Update with dynamic top value in CTE

$
0
0

Hi,

Scenario :

I have 2 main tables. One is header level and another is detail level. Each header table records have multiple detail entries based on the header table Quantity. Eg: The header have Quantity 50, detail table have 50 receords. Likwise each header table entry have Quantity based record count in the detail table.

My Question:

   User enter multiple header request in one temp table. So that based on the requested quantity the first (FIFO) or top requested number of receords needs to be updated in the detail level. For example, if user enter header 1 and quantity 25. Then update the  top 25 records in the detail table on header id is updated.

HeaderTable Name is ReceiveLot, Detail table is ReceiveSerial and temp table isStoresReferenceConsumptions (which is the table users entered the request)

I wrote the query like below

;with cte
as
(
SELECT         
B.ReceiveLotID        
,CAST(A.Quantity AS INT) Quantity       
FROM StoresReferenceConsumptions A          
INNER JOIN ReceiveLot B                             
ON A.ReferenceNumber = B.ReceiveLotID                           
WHERE A.ReferenceType=1   
)
,cte1
as ( 
SELECT 
B.ReceiveSerialID, 
B.SerialNumber 
FROM cte A 
INNER JOIN ReceiveSerial B 
ON A.ReceiveLotID = B.ReceiveLotID 
WHERE B.[Status] = 'ALLOTTED' 
) 
select * from cte1 

Here i got all the detail table values of he header id which is requested. But i can't use the top with hedaer Quantity in cte1. So how i update only the top number of records.

If i use general update query i need to use 2 subqueries . please guide me.

Actualy this is my revised query. My original query is very time consuming because i used cte inside cursor which is creating problems in production. so only i am try like this


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>