Click here to Skip to main content
15,878,814 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear Team,

I have two tables named
1.Table_Columns
2.Table_Employee

1."Table_Columns" has one column named "Columns" and it has values
Emp_ID
Emp_Name
Sum(Emp_Salary)

all above values are in single column(Named "Columns")

2."Table_Employee" has columns named below with their values
Emp_ID   Emp_Name   Emp_Salary
1        Sukhen     10000
2        Dass       20000


Now i want to write a query to retrieve all those columns from table "Table_Employee"
on the basis of columnms defined in "Table_Columns"

Thanks
Sukhen Dass


[edit]SHOUTING removed, code block added - OriginalGriff[/edit]
Posted
Updated 16-Sep-12 20:14pm
v3
Comments
OriginalGriff 17-Sep-12 2:15am    
DON'T SHOUT. Using all capitals is considered shouting on the internet, and rude (using all lower case is considered childish). Use proper capitalisation if you want to be taken seriously.

1 solution

I am not sure if i understood your question correctly. Here is a sample approach
SQL
CREATE TABLE #Table_Columns
(
	Columns VARCHAR(50)
)

CREATE TABLE #Table_Employee
(
	Emp_ID  INT IDENTITY(1,1),
	Emp_Name   VARCHAR(50),
	Emp_Salary INT
)

INSERT INTO #Table_Columns
SELECT 'Emp_ID' UNION ALL
SELECT 'Emp_Name' UNION ALL
SELECT 'Emp_Salary' 

INSERT INTO #Table_Employee
SELECT 'Sukhen', 10000 UNION ALL
SELECT 'Dass',  20000


DECLARE @Columns VARCHAR(100)
SELECT @Columns = ISNULL(@Columns,'') + Columns + ', ' FROM #Table_Columns

IF @Columns <> ''
BEGIN

	SELECT @Columns = SUBSTRING(@Columns, 1,LEN(@Columns)-1)

END

DECLARE @SQL VARCHAR(MAX)

SET @SQL = 'SELECT ' + @Columns + ' FROM #Table_Employee'

EXECUTE (@SQL)


DROP TABLE #Table_Columns
DROP TABLE #Table_Employee
 
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