Solved

How to display multiple column values as rows in my stored procedure

Posted on 2014-02-25
4
171 Views
Last Modified: 2014-03-04
I have a stored procedure that display column values like this

ID      Entity    UnitID UnitName RoleID

1        Test       1         UnitTest    1
1        Test        1        UnitTest     2
1        Test        1         UnitTest    4

As you can see all my column values are same except RoleId changes What I want to see as

ID      Entity    UnitID UnitName RoleID   RoleID1    RoleID2

1        Test       1         UnitTest    1            2              4

Instead of displaying three times I want to have one row and create some temporary columns (RoleID1 and RoleID2) to store the values and sent back the results

I'm attaching my stored procedure here and I'm using microsoft sql server 2012
StoredProce-EE.txt
0
Comment
Question by:bujjigadu
  • 3
4 Comments
 
LVL 26

Expert Comment

by:Zberteoc
Comment Utility
This is pivoting but in order to be able to do this you will have to know the maximum unittests you have and then use that to build that many columns.

To pivot:

http://blogs.msdn.com/b/spike/archive/2009/03/03/pivot-tables-in-sql-server-a-simple-sample.aspx

or:

http://www.codeproject.com/Tips/500811/Simple-Way-To-Use-Pivot-In-SQL-Query
0
 

Author Comment

by:bujjigadu
Comment Utility
For some reason the pivot table is not giving me the results I'm looking for. Is there anyway I can loop through current results and build a temp table

like loop through this result set

ID      Entity    UnitID UnitName RoleID

1        Test       1         UnitTest    1
1        Test        1        UnitTest     2
1        Test        1         UnitTest    4

and build a temp table with this result set

ID      Entity    UnitID UnitName RoleID   RoleID1    RoleID2

1        Test       1         UnitTest    1            2              4
0
 
LVL 26

Accepted Solution

by:
Zberteoc earned 355 total points
Comment Utility
You can loop but it is not recommended. Pivot exists for exact this reason, to turn column values in different rows in different column in the same row.
0
 
LVL 26

Expert Comment

by:Zberteoc
Comment Utility
Try this:

ALTER PROCEDURE [dbo].[TestingUnits_getAllUserPerms] 
	-- Add the parameters for the stored procedure here
	@UserName varchar(80), 
	@RoleID int,
	@RoundingUserName varchar(80),
	@RoundingUserRoleID int,
	@RoundingUserRoleID1 int,
	@RoundingUserRoleID2 int,
	@EntityID int 
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
SELECT * INTO #tmp
FROM
(
	    SELECT nu.EntityID,
		e.[EntityName], 
		nu.UnitID, 
		UnitName,
		nu.Active,
		r.roleid
		FROM testUnits nu
		inner join [dbo].[Entity] e on e.EntityID = nu.EntityID
		,UserRole r
		WHERE 
			(nu.EntityID = @EntityID)
			AND
			(nu.UnitID  IN (SELECT UnitID FROM UserAuthorizedUnitsInRole(@RoundingUserName, @RoundingUserRoleID)))
			AND
			(nu.UnitID  IN (SELECT UnitID FROM UserAuthorizedUnitsInRole(@UserName, @RoleID)) AND (@UserName IS NOT NULL) AND (@UserName <> ''))
			AND
			r.roleid not in (6,7)
UNION

		SELECT nu.EntityID,
		e.[EntityName], 
		nu.UnitID, 
		UnitName,
		nu.Active,
		r.roleid
		FROM testUnits nu
		inner join [dbo].[Entity] e on e.EntityID = nu.EntityID
		,UserRole r
		WHERE 
			(nu.EntityID = @EntityID)
			AND
			(nu.UnitID IN (SELECT UnitID FROM UserAuthorizedUnitsInRole(@RoundingUserName, @RoundingUserRoleID1)))
			AND
			(nu.UnitID IN (SELECT UnitID FROM UserAuthorizedUnitsInRole(@UserName, @RoleID)) AND (@UserName IS NOT NULL) AND (@UserName <> ''))
	        AND
			r.roleid not in (6,7)
UNION

		SELECT nu.EntityID,
		e.[EntityName], 
		nu.UnitID, 
		UnitName,
		nu.Active,
		r.roleid
		FROM testUnits nu
		inner join [dbo].[Entity] e on e.EntityID = nu.EntityID
		,UserRole r
		WHERE 
			(nu.EntityID = @EntityID)
			AND
			(nu.UnitID IN (SELECT UnitID FROM UserAuthorizedUnitsInRole(@RoundingUserName, @RoundingUserRoleID2)))
			AND
			(nu.UnitID IN (SELECT UnitID FROM UserAuthorizedUnitsInRole(@UserName, @RoleID)) AND (@UserName IS NOT NULL) AND (@UserName <> ''))
			AND
			r.roleid not in (6,7)

UNION

		SELECT nu.EntityID,
		e.[EntityName], 
		nu.UnitID, 
		UnitName,
		nu.Active,
		r.roleid
		FROM testUnits nu
		inner join [dbo].[Entity] e on e.EntityID = nu.EntityID
		,UserRole r
		WHERE 
			(nu.EntityID = @EntityID)
			AND
			r.roleid not in (6,7)
) q
	ORDER BY UnitName

SELECT *
FROM (
    SELECT 
        EntityID,
		EntityName, 
        UnitID,
		Active,
		UnitName,
		RoleID
    FROM 
		#tmp
) as s
PIVOT
(
    MIN(UnitName)
    FOR RoleID IN (1,2,3,4,5,6,7,8,9,10)
)AS pivot
END

Open in new window

If you have more than 10 RoleID values you will have to increase to maximum:

 FOR RoleID IN (1,2,3,4,5,6,7,8,9,10.....)
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Noob question:this site is sql vulns? 2 42
SQL Connection (Error 18456) 14 29
SQL JOIN 6 31
Sql query 34 16
In this article—a derivative of my DaytaBase.org blog post (http://daytabase.org/2011/06/18/what-week-is-it/)—I will explore a few different perspectives on which week today's date falls within using Microsoft SQL Server. First, to frame this stu…
Everyone has problem when going to load data into Data warehouse (EDW). They all need to confirm that data quality is good but they don't no how to proceed. Microsoft has provided new task within SSIS 2008 called "Data Profiler Task". It solve th…
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function

743 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

14 Experts available now in Live!

Get 1:1 Help Now