If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Data Access, Manipulation & Batch Languages > ANSI SQL > Table name in a stored procedure

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 03-09-04, 04:47
gutoim gutoim is offline
Registered User
 
Join Date: Dec 2003
Location: Romania
Posts: 4
Table name in a stored procedure

How can be used in a stored procedure the name of a table that was passed as a varchar parameter? The table name must be used in the "from" clause of a "select" statement without calling the "EXECUTE" or "sp_executesql". Is it possible?
Marius G.
Reply With Quote
  #2 (permalink)  
Old 03-09-04, 08:39
ClaireHsu ClaireHsu is offline
Registered User
 
Join Date: May 2003
Location: Parsippany NJ
Posts: 36
yes

create procedure usp_tableget @tbname varchar(100)
as
exec('select * from '+@tbname)
Reply With Quote
  #3 (permalink)  
Old 03-09-04, 10:27
Pat Phelan Pat Phelan is offline
Resident Curmudgeon
 
Join Date: Feb 2004
Location: In front of the computer
Posts: 12,605
I'll assume from your references that you are dealing with Microsoft SQL. The answer is essentially the same no matter which SQL engine you are using, although the implementation details are different.

There are ways to do it, but they all involve dynamic SQL of some sort. Obviously you can get there via EXECUTE ('SELECT * FROM ' + @t) and similar tricks using sp_sqlexec, but you've ruled those out. You can also get there via OPENQUERY, and via all kinds of twists that do basically the same kind of thing.

You are asking for dynamic SQL. You may have to live with getting dynamic SQL!

-PatP
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On