---sql: T-SQL 統(tǒng)計(jì)計(jì)算(父子關(guān)係,樹形,分級(jí)分類的統(tǒng)計(jì))---2014-08-26 塗聚文(Geovin Du)CREATE PROCEDURE proc_Select_BookKindSumReportASDECLARE @temp TABLE( BookKindID INT IDENTITY(1, 1) , BookKindName VARCHAR(10), BookKindParent int, BookKindSum int )--declare @id int,@grouid nvarchar(500),@sql nvarchar(4000),@cstucount int,@c intDECLARE @tempId INT , @tempName VARCHAR(10), @tempParent intdrop table #tempselect * into #temp from BookKindListWHILE EXISTS ( SELECT BookKindID FROM #temp ) BEGIN SET ROWCOUNT 1 SELECT @tempId = [BookKindID] , @tempName = [BookKindName],@tempParent=BookKindParent FROM #temp SET ROWCOUNT 0 --delete from #temp where BookKindID = @tempId set @id=@tempId select @grouid=dbo.GetBookKindGroupId (@id)select @sql='SELECT @c=count(*) FROM BookInfoList where BookInfoKind in ('+@grouid+')'--exec (@sql)exec sp_executesql @sql,N'@c int output',@cstucount output--將exec的結(jié)果放入變量中的做法 --select @cstucount as 'sum' --PRINT '記錄:----'+ cast(@tempId as varchar(20))+',' + @tempName+','+ cast(@tempParent as varchar(20))+' sum:'+ cast(@cstucount as varchar(50))insert into @temp(BookKindName,BookKindParent,BookKindSum) values(@tempName,@tempParent,@cstucount)ENDselect * from @temp order by BookKindParentGO--利用游標(biāo)來遍歷表--定義表變量DECLARE @temp TABLE( BookKindID INT IDENTITY(1, 1) , BookKindName VARCHAR(10), BookKindParent int) DECLARE @tempId INT , @tempName VARCHAR(10),@tempParent intDECLARE test_Cursor CURSOR LOCAL FORSELECT BookKindID,BookKindName,BookKindParent FROM @temp--插入數(shù)據(jù)值INSERT INTO @temp VALUES ( 'a',1 ) INSERT INTO @temp VALUES ( 'b',2 )INSERT INTO @temp VALUES ( 'c',3 )INSERT INTO @temp VALUES ( 'd',4 ) INSERT INTO @temp VALUES ( 'e',5 ) --打開游標(biāo)OPEN test_CursorWHILE @@FETCH_STATUS = 0 BEGIN FETCH NEXT FROM test_Cursor INTO @tempId,@tempname,@tempParent PRINT '記錄:----' + cast(@tempId as varchar(20))+',' + @tempName+','+ cast(@tempParent as varchar(20)) END CLOSE test_CursorDEALLOCATE test_Cursor
新聞熱點(diǎn)
疑難解答
圖片精選