Nothing very original - a suggestion for implementing the ideas already given, and for amnding the SQL to run as a simple SELECT statement:
--DDL:
create table custlist(id int identity(1,1), custid int, spid int)
--Query:
set nocount on
set ansi_warnings off
declare @spid int, @filepath varchar(255), @bcp varchar(2000), @password varchar(20)
set @spid = @@spid
set @filepath = '\\share\dir\...\dir\filename.extension'
set @bcp = 'bcp in db.owner.custlist '+ @filepath +' -f custid_only.fmt -S SERVERNAME -U USERID -P ' + @password
set transaction isolation level serializable
begin tran
exec xp_cmdshell(@bcp)
update custlist set spid = @spid
where spid is null
commit
set transaction isolation level read committed --(or whatever your current setting was)
select
c.id,
c.phone,
c.fullname,
c.lastname,
c.firstname,
isnull(
sum(
case when oh.date_delivery between '1/1/03' and '2/14/03'
then 1
else 0
end
)
,0) PriorCount,
isnull(
sum(
case when oh.date_delivery between '1/1/03' and '2/14/03'
then
IsNull(oh.revenue_food,0)
+ isnull(oh.revenue_house,0)
+ isnull(oh.revenue_convfee,0)
+ isnull(oh.revenue_delfee,0)
- isnull(revenue_discount, 0)
else 0
end
)
,0) PriorSales,
isnull(
sum(
case when oh.date_delivery between '2/15/03' and '3/31/03'
then 1
else 0
end
)
,0) AfterCount,
isnull(
sum(
case when oh.date_delivery between '2/15/03' and '3/31/03'
then
IsNull(oh.revenue_food,0)
+ isnull(oh.revenue_house,0)
+ isnull(oh.revenue_convfee,0)
+ isnull(oh.revenue_delfee,0)
- isnull(revenue_discount, 0)
else
0
end
)
,0) AfterSales
from customers c
join custlist cl
on cl.custid = c.id
and cl.spid = @@spid
left join orderheader oh
on oh.customerid = c.id
where c.companyid = 1154
and oh.ordertype = 1
and oh.companyid = 1154
delete custlist where spid = @spid
Tim Wilkinson
"If it doesn't work in practice, you're using the wrong theory"
- Immanuel Kant