Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take table name as an input parameter to the stored procedure?

Tags:

I have a small stored procedure below.

I am taking the table name as an input parameter to the stored procedure so that I'm planning to insert the data into the temp table and display the same. This is just a tiny code block of my project stored procedure.

When I am compiling the below, it is considering the parameter in the select statement as a table variable and throwing the error as:

Must declare the table variable "@TableName".

SQL:

CREATE PROCEDURE xyz @TableName Varchar(50)  AS  BEGIN  SELECT TOP 10 * INTO #Temp_Table_One  FROM @TableName   SELECT * FROM #Temp_Table_One  END 
like image 286
chandra sekhar Avatar asked Feb 28 '14 20:02

chandra sekhar


People also ask

Can we pass table name as parameter in stored procedures?

Unfortunately, you can't use a variable containing the table name in an INSERT statement. The error message is actually occurring because it is expecting a variable that is a table type to insert rows into, but you're passing a variable with a string value.

How do I fetch a table name?

The syntax to get all table names with the help of SELECT statement. mysql> use test; Database changed mysql> SELECT Table_name as TablesName from information_schema. tables where table_schema = 'test'; Output with the name of the three tables.


2 Answers

CREATE PROCEDURE xyz  @TableName NVARCHAR(128)  AS  BEGIN    SET NOCOUNT ON;   DECLARE @Sql NVARCHAR(MAX);  SET @Sql = N'SELECT TOP 10 * INTO #Temp_Table_One                FROM ' + QUOTENAME(@TableName)           + N' SELECT * FROM #Temp_Table_One '   EXECUTE sp_executesql @Sql  END 
like image 71
M.Ali Avatar answered Oct 07 '22 14:10

M.Ali


use sql dynamic

try

CREATE PROCEDURE xyz @TableName Varchar(50)  AS  BEGIN   DECLARE @query  set @query = 'SELECT TOP 10 * FROM '+ @TableName   EXEC @query END 

add schema name.

eg:

exec xyz @TableName = 'dbo.mytable'

exec xyz @TableName = 'myschema.mytable'

like image 25
LuisR9 Avatar answered Oct 07 '22 13:10

LuisR9