Solved

Sql Stored Procedure

Posted on 2013-12-06
2
342 Views
Last Modified: 2013-12-06
Hi Experts

I would like to build a sp in mssql for the attached file with question and target answer

That's all

Thanks
Book1.xlsx
0
Comment
Question by:beckyng
2 Comments
 
LVL 34

Expert Comment

by:Brian Crowe
ID: 39701221
SELECT Parent, Child, Level, Hierachy, Usage,
   Usage * CASE WHEN Level = 1 THEN 1 ELSE (SELECT Usage FROM MyTable WHERE Level = 1) END AS [New Usage]
FROM myTable AS T
0
 
LVL 11

Accepted Solution

by:
John_Vidmar earned 350 total points
ID: 39701462
-- test data
select	Parent	= 'P001'
,	Child	= 'C002'
,	Usage	= 2.000
into	#temp
union all
select	Parent	= 'C002'
,	Child	= 'K003'
,	Usage	= 1.000
union all
select	Parent	= 'K003'
,	Child	= 'T001'
,	Usage	= 0.027
go

-- recursive call
WITH
	recursive_CTE
	(	Parent
	,	Child
	,	Hierarchy
	,	Usage
	,	Level
	)
	AS
	(
		SELECT	a.Parent
		,	a.Child
		,	CAST(a.Parent +'.'+ a.Child as varchar(50))
		,	CAST(a.Usage as numeric(9,3))
		,	1
		FROM	#temp	a
		LEFT
		JOIN	#temp	b	ON	a.Parent = b.Child
		WHERE	b.Child IS NULL

		UNION ALL

		SELECT	b.Parent
		,	b.Child
		,	CAST(a.Hierarchy + '.' + b.Child as varchar(50))
		,	CAST(a.usage * b.usage as numeric(9,3))
		,	a.Level + 1
		FROM	recursive_CTE	a
		JOIN	#temp		b	ON	a.Child = b.Parent
		
	)
SELECT	Parent
,	Child
,	Level
,	Hierarchy
,	Usage
FROM	recursive_CTE

Open in new window

0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

SQL Server engine let you use a Windows account or a SQL Server account to connect to a SQL Server instance. This can be configured immediatly during the SQL Server installation or after in the Server Authentication section in the Server properties …
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now