Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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
Updated 15-Nov-12 22:33pm
v2
Comments
joshrduncan2012 16-Nov-12 12:37pm    
What have you done to try to solve this problem?

1 solution

Try something like this:

SQL
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)
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900