0

I want to create a table from this code in SQL Server, but the stored procedure returns an error

CREATE PROCEDURE Recovery_CountryCode (@NombreTabla SYSNAME)
AS
DECLARE @ParamDefinition nvarchar(500);
DECLARE @SQLString nvarchar (4000);
 SET @SQLString=N'SELECT Name
                INTO @TableName
                FROM AdventureWorks2008R2.Production.Location';
SET @ParamDefinition=N'@TableName SYSNAME';
EXECUTE sp_executesql @SQLString, @ParamDefinition, @TableName=@NombreTabla;
GO

I want avoid define table

When I call the stored procedure:

EXEC Recovery_CountryCode @NombreTabla='Paises';

I get the follow message:

Mens. 102, Nivel 15, Estado 1, Línea 2 Sintaxis incorrecta cerca de '@TableName'.

1
  • Here is similar problem and solution.
    – Robert
    Nov 14, 2012 at 22:45

2 Answers 2

1

You can just concatenate the SQL inside your procedure

CREATE PROCEDURE Recovery_CountryCode (@NombreTabla SYSNAME)
AS
DECLARE @ParamDefinition nvarchar(500);
DECLARE @SQLString nvarchar (4000);
 SET @SQLString=N'SELECT Name INTO ' + 
                @NombreTabla + 
                ' FROM AdventureWorks2008R2.Production.Location';
EXECUTE sp_executesql @SQLString
GO
0

You can't bind variables to table names in this way. You need to do something like

Declare @sql nvarchar(max), @NombreTable sysname = 'Test'

Set @sql = N'Select Name Into ' + @NombreTable +
           N' From AdventureWorks2008R2.Production.Location

exec sp_executesql @sql

http://www.sommarskog.se/dynamic_sql.html is recommended reading.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.