I have one table in one of its column it stored column name of another
table. i want select statement to select that column name. i will explain
this with example
Table1 has columns with name ID,col1 and having data in that column as
(1,tb_col1),(2,tb_col2),(3,tb_col3) etc
and another table has this columndata of table one as column name means
table2 has column (tab_id2,tb_col1,tb_col2,tb_col3)
inthis if i select ID=1 from table1 then select statement should show me
data in column tb_col1 of table2..
if i select ID=2 from table1 then select statement should show me data in
column tb_col2 of table2..
here data in column col1 of table1 may change any time so i want it
dynamically
Message posted via http://www.webservertalk.comYou need to use dynamic sql.
Example:
create procedure dbo.proc1
@.id int
as
set nocount on
declare @.sql nvarchar(4000)
if exists(select * from table1 where [id] = @.id)
begin
set @.sql = N'select [' + (select top 1 col1 from table1 where [id] =
@.id) + N'] from table2'
exec sp_executesql @.sql
end
return @.@.error
go
exec dbo.proc1 1
exec dbo.proc1 2
go
The Curse and Blessings of Dynamic SQL
http://www.sommarskog.se/dynamic_sql.html
AMB
"Malkesh Sheth via webservertalk.com" wrote:
> I have one table in one of its column it stored column name of another
> table. i want select statement to select that column name. i will explain
> this with example
> Table1 has columns with name ID,col1 and having data in that column as
> (1,tb_col1),(2,tb_col2),(3,tb_col3) etc
> and another table has this columndata of table one as column name means
> table2 has column (tab_id2,tb_col1,tb_col2,tb_col3)
> inthis if i select ID=1 from table1 then select statement should show me
> data in column tb_col1 of table2..
> if i select ID=2 from table1 then select statement should show me data in
> column tb_col2 of table2..
> here data in column col1 of table1 may change any time so i want it
> dynamically
> --
> Message posted via http://www.webservertalk.com
>|||>> I have one table in one of its column it stored column name of
another table. <<
This is called mixing data and metadata. Good SQL programmers do not
write code like this! Bad SQL programmers use Dynamic SQL and lose
their data integrity.
Showing posts with label anothertable. Show all posts
Showing posts with label anothertable. Show all posts
Sunday, February 19, 2012
Subscribe to:
Posts (Atom)