Click here to Skip to main content
Rate this: bad
good
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 23:09pm
Edited 15-Nov-12 23:33pm
Nelek66.5K
v2
Comments
joshrduncan2012 at 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
0 Sergey Alexandrovich Kryukov 8,963
1 OriginalGriff 6,726
2 Peter Leow 4,232
3 Zoltán Zörgő 3,769
4 Richard MacCutchan 2,558


Advertise | Privacy | Mobile
Web01 | 2.8.150123.1 | Last Updated 16 Nov 2012
Copyright © CodeProject, 1999-2015
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