Click here to Skip to main content
12,406,592 members (50,912 online)
Rate this:
 
Please Sign up or sign in to vote.
i need a stored procedure which can fetch values from 2 tables. for eg-

table A
id - name
1  - x
2 -  y

table B
id- text- value
1 -  X  -   X1
1  - Y -    Y1
1  - Z -    Z1
2  - A -    A1
2 -  B  -   B1

now if i fetch value from these two tables where id =1 , then the result should me diplyes like

id- name- X- Y - Z
1 -  x  - X1- Y1- Z1


so we need text as a column name and value as a column values.

[edit]text block added[/edit]
Posted 15-Nov-12 22:09pm
Updated 15-Nov-12 22:33pm
Nelek96.6K
v2
Comments
joshrduncan2012 16-Nov-12 12:37pm
   
What have you done to try to solve this problem?

1 solution

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

Try something like this:

DECLARE @cols NVARCHAR(300)
DECLARE @dt NVARCHAR(1000)
DECLARE @pt NVARCHAR(2000)
 
SET @cols = STUFF((SELECT DISTINCT '],[' + [Name]
					FROM A
					ORDER BY '],[' + [Name]
			FOR XML PATH('')),1,2,'') + ']'
 
SET @dt = 'SELECT B.[ID], B.[Text], B.[Value] ' +
		'FROM A LEFT JOIN B ON A.[ID] = B.[ID] '
--EXEC(@dt)

SET @pt = 'SELECT [ID], ' + @cols + ' ' +
		'FROM (' + @dt + ') AS DT ' +
		'PIVOT(MAX([Value]) FOR [Text] IN (' + @cols + ')) AS PT ' + 
		'ORDER BY [ID]'
EXEC(@pt)
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web02 | 2.8.160730.1 | Last Updated 16 Nov 2012
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100