Sql return table information by username

I would like to receive all table information for the submited tablename in a stored procedure.

For example something like this :

create proc selectUserTable 
@username nvarchar(30)
as
begin
select * from @username
end

Of course this doesn't work, but how can I make something like that?

If I do this:

create proc selectUserTable 
@username nvarchar(30)
    as
    begin
SELECT * FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_NAME LIKE '@username'
end

It will only return the tablename not the information in it.

Answers


You need dynamic query, but be aware of sql injection:

create proc selectUserTable 
@username nvarchar(30)
as
begin
  Exec('select * from ' +  @username)
end

If @tablename = 'users; drop table users;', you will be in trouble. Better first get objectid by tablename variable then again get objectname by objectid and pass it to exec function, rather then passing tablename variable directly.


Need Your Help

Is there a specific design pattern for managing YAML aliases in large files?

design-patterns yaml data-modeling data-files

I have a big YAML file that stores test cases for my app. It uses a lot of anchors and alias to share parts among test cases. It was initially ok to manage, but it now seems to have outgrown from w...

Caching preloaded images possible over page switch?

javascript html image

I'm currently trying to preload images for a webpage I'm creating as those images are quite big.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.