Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: SQL
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 16-Sep-12 21:06pm
Edited 16-Sep-12 21:14pm
v3
Comments
OriginalGriff at 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

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

Solution 1

I am not sure if i understood your question correctly. Here is a sample approach
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
  Permalink  

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

  Print Answers RSS
0 OriginalGriff 565
1 Maciej Los 319
2 Richard MacCutchan 220
3 BillWoodruff 164
4 Mathew Soji 160
0 OriginalGriff 8,654
1 Sergey Alexandrovich Kryukov 7,407
2 DamithSL 5,639
3 Maciej Los 5,229
4 Manas Bhardwaj 4,986


Advertise | Privacy | Mobile
Web03 | 2.8.1411023.1 | Last Updated 17 Sep 2012
Copyright © CodeProject, 1999-2014
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