How to put the table name as a variable in a SQL Server query?

I am new to this of SQL Server and I want to create an SP that lists me all the data of a table, but having as variable the table to query.

I had thought something like this:

CREATE PROCEDURE SP_LISTAR_TODOS
(@tabla )
AS
SELECT * FROM @tabla

Clearly, the data type @tabla is missing, or is there another way to do that?

This is my doubt, thank you.

 2
Author: Vicky Vicent, 2016-06-11

3 answers

You want to create a Stored Procedure to select the data from a table, the table variable will be received as parameter:

CREATE PROCEDURE SP_LISTAR_TODOS 
@tabla NVARCHAR(128) 
AS 
BEGIN 
  SET NOCOUNT ON;
  DECLARE @Sql NVARCHAR(MAX);

  SET @Sql = 'SELECT * FROM ' + QUOTENAME(@tabla)     
  EXEC sp_executesql @Sql

END
 2
Author: Jorgesys, 2016-06-12 02:15:49

You can try the EXECUTE statement, which interprets the assigned string as a series of SQL commands

EXECUTE format('SELECT * FROM %s', @tabla)
INTO result;
 0
Author: Joel Ibaceta, 2016-06-11 21:49:21

Excellent contribution, I was looking to find the maximum value in a field of a table whose name is variable. the key is in QUOTENAME (@Table) and use EXEC sp_executesql @Sqldos

I used this code:

SET NOCOUNT ON   DECLARE @Sqldos NVARCHAR(MAX);    
SET @Sqldos = 'SELECT max(idtablaimsa) as puto FROM ' + QUOTENAME(@nomtabla)   
     EXEC sp_executesql @Sqldos

Thank you!

 0
Author: Diego Magan, 2016-06-22 20:31:25