Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1331
  • Last Modified:

variable tablename ?

I execute a stored procedure out of VB4.
In this stored procedure there is a SELECT FROM statement.
The problem is that I wanna use the sp to select from different tables. So there is my question:

Can I supply the tablename as a varible?
for example:

sp_get
@tablename char(25)

SELECT * FROM @tablename
0
tell
Asked:
tell
  • 2
1 Solution
 
cymbolicCommented:
No you can't use a parameter for the table name.  A stored procedure is compiled to present an optimized query plan, based upon the tables involved and the columns access/filtered.

The best you can do is to create multiple differently named stored procedures (name them based upon table target table name), and then use a variable name to substitute the procedure name that works with the table you desire at run time.
0
 
Victor SpiridonovCommented:
Yes you can use tablename as a parameter.

CREATE PROCEDURE testt @tabname varchar(30)
AS
DECLARE @sql VARCHAR(100)
SELECT @sql="SELECT * FROM "+@tabname
EXEC(@sql)

0
 
tellAuthor Commented:
I would like to grade spirididonov with an AAA.
Thanks a lot !
0
 
Victor SpiridonovCommented:
If you want to grade my answer you should have rejected the proposed answer. Or otherwise post the points as another question

0

Featured Post

NFR key for Veeam Backup for Microsoft Office 365

Veeam is happy to provide a free NFR license (for 1 year, up to 10 users). This license allows for the non‑production use of Veeam Backup for Microsoft Office 365 in your home lab without any feature limitations.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now