ALTER PROCEDURE [dbo].[sp_GetBalance] @userid nvarchar(50), @fdate datetime, @tdate datetime AS BEGIN
if OBJECT_ID('[#temptable]') is not null drop table [#temptable] go create table [#temptable]([id] bigint,[userid] nvarchar(50),[receivable] decimal(18, 2),[paid] decimal(18, 2),[balance] decimal(18, 2),[indate] datetime) insert [#temptable] SELECT a.id,a.userid, a.receivable, a.paid, (SELECT SUM(receivable) - SUM(paid) AS Expr1 FROM dbo.FundDetail_out WHERE (id <= a.id)) AS balance, a.indate FROM dbo.FundDetail_out a where userid = @userid
select * from [#temptable] where indate between @fdate and @tdate END