How to Validate Tables in Dynamic SQL

This is for homework, the reading & provided notes  are exteremly light. one of the homework problems requires me to pass a column and table varchar to a procedure.

for which i have....
create proc proc_test
@col varchar(max),
@table varchar(max)
declare @sql_string varchar(max)

set @sql_string = 'select ' + @col + ' from ' + @table;
exec (@sql_string);

Now, the next part of the assignment has me validating the @table variable is in fact a table within the database and not some inserted code.(delete, drop, insert, etc.)

I changed the @table to a sysname variable but that does not seem right to me.

Any insight is appreciated.....or a go here read this would be grand.thanks
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

You could use systems views in sql 2005 and 2008
or SELECT name FROM dbo.sysobjects WHERE xtype = 'U'  see code

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(@table) AND type = 'D')
....your code 

Open in new window

Using the dbo.sysobjects the  type should be 'U' and not 'D', please see code.
You have other methods to list tables within the database like
declare @table nvarchar(250)
set @table='List1'
SELECT * FROM information_schema.Tables
Where Table_Name =@table

SELECT * FROM sys.Tables
Where Name =@table

declare @table nvarchar(max)
set @table='dbo.List1'
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(@table) AND type in ('U'))
---Your code

Open in new window


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
cflores89Author Commented:
Perfect!  I actually use teh schema.Tables suggestion
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.