SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Update target table using metadata and source tabl
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

flamblaster
Constraint Violating Yak Guru

380 Posts

Posted - 10/04/2013 :  21:30:12  Show Profile  Reply with Quote
Hey guys,

I'd like to figure out how to use the @FieldDescription table below as an intermediate table between the @SourceData and @Stops data. Any ideas?
declare @Stop table (StopId int, UserField varchar(20))
declare @FieldDescription table (Label varchar(10), ColumnName varchar(10))
declare @UpdateSource table (HasPathway varchar(10))

insert into @Stop (StopId, UserField)
values (1, 'Yes')

insert into @FieldDescription (Label, ColumnName)
values ('HasPathway', 'UserField')

insert into @UpdateSource (HasPathway)
values ('No')

I want to update @Stop.UserField with thevalue from @UpdateSource where @UpdateSource.HasPathway=@Stop.UserField...but I need to use the @FieldDescription table to determine how to map the columns.

khtan
In (Som, Ni, Yak)

Singapore
17440 Posts

Posted - 10/06/2013 :  03:37:30  Show Profile  Reply with Quote
you will need to use Dynamic SQL

take a look at this http://www.sommarskog.se/dynamic_sql.html


KH
Time is always against us

Go to Top of Page

flamblaster
Constraint Violating Yak Guru

380 Posts

Posted - 10/06/2013 :  23:11:56  Show Profile  Reply with Quote
thanks Khtan,

I'm generating a script using information_schema.columns to update columns in the target table from the source. I'll try to wrap it up in dynamic sql. thanks for the tip!
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
52249 Posts

Posted - 10/07/2013 :  05:40:33  Show Profile  Reply with Quote

SELECT *
FROM
(
SELECT m.StopId,m.Col,v.Val
FROM
(
SELECT StopId,Col,Val
FROM @stop s
UNPIVOT (Val FOR Col IN ([UserField],..any other columns you want))u
)m
JOIN @FieldDescription fd
ON fd.ColumnName = m.Col
JOIN (
SELECT Col,Val
FROM @UpdateSource  u
UNPIVOT (Val FOR Col IN ([HasPathway],..any other columns you want))u
)n
ON n.Col = fd.Label
)t
PIVOT (MAX(Val) FOR Col IN (([UserField],..any other columns you want))p


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.09 seconds. Powered By: Snitz Forums 2000