Te recomiendo que utilices procedimiento almacenado y después lo llamas, que seria algo asi:
Create
Procedure Socios(
@fecha1
asdatetime,
@fecha2
asdatetime)
as
begin
select
T0.cardcode, T0.cardname, T0.balance as SALDO,
ISNULL
((SELECTSUM(A0.DocTotal)FROM ORDR A0 WHERE A0.CardCode=T0.CardCode and A0.docdate between @fecha1 and @fecha2),0)AS PEDIDOS,
T0
.creditline as LIMITECRED, V1.slpname,
(
ISNULL((SELECTSUM(A0.DocTotal)FROM ORDR A0 WHERE A0.CardCode=T0.CardCode and A0.docdate between @fecha1 and @fecha2),0)
+(t0.balance)-(t0.creditline))AS TOTAL,
ISNULL
((SELECTcount(A0.DocTotal)FROM ORDR A0 WHERE A0.CardCode=T0.CardCode and A0.docdate between @fecha1 and @fecha2),0)AS conteo
from
ocrd T0
join
ordr T1 on T0.cardcode = T1.cardcode
join
oslp V1 on T0.slpcode = V1.slpcode
where
T1.docdate between @fecha1 and @fecha2
group
by T0.cardcode, T0.cardname, T0.balance, V1.slpname, t0.creditline
order
by TOTAL DESC
end