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

梦想的初衷 提交于 2019-11-30 08:22:14

问题


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

回答1:


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



回答2:


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'



来源:https://stackoverflow.com/questions/22105121/how-to-take-table-name-as-an-input-parameter-to-the-stored-procedure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!