I have written a query which works great on my local SQL Server 2005. I uploaded the query to my hosting server and somehow they say that temporary table creation is disabled on their server.
My query looks like this
create table #tmp
(
srno int identity (1,1) ,
orderid int,
orderdate datetime,
product_code varchar(255),
product_name varchar(255),
shipping_cost decimal(18,2)
)
insert into #tmp (orderid, orderdate, product_code, product_name, shipping_cost)
(select distinct
ord.orderid, ord.orderdate, odn.productcode,
odn.productname, ord.totalshippingcost
from OrderNew ord
inner join order_detailsnew odn on ord.orderid = odn.orderid)
declare @rowcount int, @flag int, @orderid int
set @rowcount = (select @@ROWCOUNT)
set @flag = 0
while (@flag <@rowcount)
begin
set @orderid = (select orderid from #tmp where srno = @flag + 1)
if exists (select 1 from #tmp where orderid = @orderid )
begin
update #tmp
set shipping_cost = 0.0
where srno IN (select srno from #tmp
where orderid = @orderid
AND srno NOT IN (SELECT TOP 1 srno FROM #tmp where orderid = @orderid))
end
set @flag = @flag+1
end
select * from #tmp
drop table #tmp
So not sure if this query can be written without a temporary table, joins etc not sure if it will work ? Any advise ?
I presume this query is to feed into a report which is why you only want the total shipping cost once, while you don’t need a temp table for this for reference you can always do this instead if you need to:
and use @tmp rather than #tmp
But you shouldn’t need a temp table for this, see below:
Works fine for me with the following test script:
And my results:
edit: I wasn’t happy with the above solution, here’s a uch faster and more elegant way of doing it:
Results match perfectly.
Edit for user580950, to insert nulls into every second row:
You change the first SELECT line to be:
And you chance the ORDER BY line to be:
But as the comments say said in your other question SQL Query Add an Alternate Blank Records, this is something that you should be doing at your presentation layer and not in the database.