Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 How to use table parameter to input a tablename

Author  Topic 

jamlogg
Starting Member

10 Posts

Posted - 2010-08-30 : 17:37:05
Hi,

I have to use a query that would allow me to enter any tablename that all have the same fields from the database 'x' when prompted. How can this be done in sql server? here is the query i wrote so far.

creat Proc (@tablename varchar(10), @Id int, @date date)
as
select * from @tablename ---> this is where the problem is
and @Id = table.field
and date = '02/28/10'

I get error message 'msg 1087: must declare table variable '@tablename'. Any help will be appreciated

K.G

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-08-30 : 17:53:01
Read this fully: http://www.sommarskog.se/dynamic_sql.html

To summarize, this is a BAD idea!

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

jcelko
Esteemed SQL Purist

547 Posts

Posted - 2010-08-30 : 19:52:29
>> I have to use a query that would allow me to enter any tablename that all have the same fields [sic: columns are not fields]from the database 'x' when prompted. <<

This is not how you program in SQL. A table represents a set of one kind of entity or relationship. You want a magical, universal procedure that treats automobiles, squids and anything in the universe alike.

You also used the reserved word DATE for a column name, did not use ISO-8601 date formats and have a magical "id" that identifies anything in the universe. That is numerology and not RDBMS.

Information about the physical nature of the tables is obtained with schema level metadata functions, not in the database.


--CELKO--
Books in Celko Series for Morgan-Kaufmann Publishing
Analytics and OLAP in SQL
Data and Databases: Concepts in Practice
Data, Measurements and Standards in SQL
SQL for Smarties
SQL Programming Style
SQL Puzzles and Answers
Thinking in Sets
Trees and Hierarchies in SQL
Go to Top of Page
   

- Advertisement -