
select top 10 * from tbTransactionSupplyOrder with(nolock)
where EntityID = 875
order by 1 desc


declare @SupplyOrderId bigint = 2104537

DECLARE @SystemAutoReceive INT = 8
DECLARE @UserAutoReceive INT = 256
SELECT 
		tso.iTransaction_num AS OrderNumber, 
    tso.TransactionSalesOrderId AS SalesOrderNumber, 
		Case When tso.CreatedFromOrder = 0 Then NULL Else tso.CreatedFromOrder End AS OriginalOrderNumber, 
		e.StoreNumber AS StoreNumber, 		    	
    	tso.iEntry_dt AS Date, 
		tso.sVendor_nm AS Vendor, 
		v.VendorNumber AS VendorNumber,
		tso.iEntry_dt AS DatePlaced,
		tso.DistributionGoodsDispatchedDate AS DateShipped,
		tso.iReceived_dt AS DateReceived,
		tso.iApply_dt AS DateApplied,
		tsa.iEntry_dt AS DateCreated,
		tso.iRequired_dt AS CoverUntil,
		Case When (((AutoStatus & @SystemAutoReceive) = @SystemAutoReceive) OR
		    		((AutoStatus & @UserAutoReceive) = @UserAutoReceive))
				Then 'TRUE' Else 'FALSE' End AS AutoReceived,
		CASE WHEN tso.iStatus_typ = 1 THEN 
			'Placed'
		ELSE
		CASE WHEN tso.iStatus_typ = 4 THEN
			'Received'
		ELSE
			tso.[sStatus]
		END END	AS OrderStatus,
		CASE WHEN tsa.SuggestedOrderingStatus = 0 THEN
			'Usage Ordering'
		ELSE  
		CASE WHEN tsa.SuggestedOrderingStatus = 1 THEN
			'Suggested Values Used'
		ELSE
		CASE WHEN tsa.SuggestedOrderingStatus = 2 THEN
			'Suggested Values Auto Cleared'
		ELSE
		CASE WHEN tsa.SuggestedOrderingStatus = 3 THEN
			'Values Manually Cleared'
		ELSE
			''
		END END	END	END AS [SuggestedStatus],
		ISNULL(FORMAT(ROUND(tsa.ForecastRange, 2), '###0.00'), '') AS [ForecastRange],
		CASE
			WHEN tso.DistributionGoodsDispatched = 1 THEN tso.sYourReference
		ELSE ''
		END AS [DistributorInvoiceNumber]
FROM tbTransactionSupplyOrder tso WITH(NOLOCK)
	JOIN tbTransactionSalesOrder tsa WITH(NOLOCK)
		ON tso.TransactionSalesOrderID = tsa.iTransaction_num
  	JOIN tbEntity e WITH(NOLOCK) 
		ON tso.EntityId = e.entityId
  	JOIN tbVendor v WITH(NOLOCK) 
		ON v.VendorId = tso.sVendor_cd
WHERE tso.iTransaction_num = @SupplyOrderId 





