Solved

Sql Stored Procedure

Posted on 2013-12-06
2
344 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

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Oracle DB monitor SW 21 47
Need some help to cast ntext to nvarchar SQL 2000 7 31
Update a text value in another table 10 37
SQL view 2 26
In this article I will describe the Copy Database Wizard method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
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 backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.

805 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