Solved

UDF to return 'select * from @tablename'

Posted on 2007-12-03
3
389 Views
Last Modified: 2008-03-03
We have a lot of existing code that refers to table 'Purchases'  Now are getting new clients and want to run the same code but using the new client's purchase tables (Purchases_ad,Purchases_nl etc).

 So I thought a function fn_purchases(whichTable) would do the trick.   The select statement would be  'select * from @tableName.'.  But no go.  I've tried  select @query = 'select * from ' + @tableName. And a variety of other attempts that don't work.

Any hints how this might be done.

thanks,

jim

0
Comment
Question by:studioEtc
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 143

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 500 total points
ID: 20398301
you cannot use a UDF to run dynamic sql. the only thing you can do is a big IF ELSE IF ... etc to decide which query to run, but then again, the output must be common among all the possible tables.

if that is not possible, you have to use a stored procedure...
0
 

Author Comment

by:studioEtc
ID: 20398395
Thanks!

If I use a stored procedure can I say 'select * from myStoredProcedure(@tableName)'?

Maybe it's better to truncate then repopulate the Purchases Table with data for the client in question before running our code.
0
 
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 20398456
>If I use a stored procedure can I say 'select * from myStoredProcedure(@tableName)'?
unfortunaltey, no.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Via a live example, show how to shrink a transaction log file down to a reasonable size.

734 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question