SQL Server将变量作为列名称

时间:2014-06-21 10:43:44

标签: sql sql-server

 CREATE PROCEDURE SPAnonymUserData 
 (
   @Table NVARCHAR (64),
   @Id INT,
   @Name nvarchar(255)
 ) AS 
   SET NOCOUNT ON; 
   DECLARE @SQL NVARCHAR(4000); 
   DECLARE @ParameterDefinition NVARCHAR(4000); 
   SELECT @ParameterDefinition = ' @IdParameter INT,
          @NameParameter nvarchar(255)';
   SELECT @SQL = N' insert into ' + @Table + '([Id],[Name])
   Values
         (' + CAST(@Id AS nvarchar(max)) + ',' + CAST(@Name AS nvarchar(max)) + ')';

 EXEC sp_executeSQL @SQL, @ParameterDefinition, @IdParameter = @Id, @Name=@Name;

如果我给出名字" Name1",服务器正在使用" Name1"作为列名....请帮助

1 个答案:

答案 0 :(得分:1)

请尝试在输入数据之前和之后插入单引号。

CREATE PROCEDURE SPAnonymUserData 
(
    @Table NVARCHAR (64),
    @Id INT,
    @Name nvarchar(255)
) 
 AS 
 SET NOCOUNT ON; 
 DECLARE @SQL NVARCHAR(4000); 
 DECLARE @ParameterDefinition NVARCHAR(4000); 
 SELECT @ParameterDefinition = ' @IdParameter INT,
 @NameParameter nvarchar(255)';
 SELECT @SQL = N' insert into ' + @Table + '
( [Id], [Name] )
values
(' +
CAST(@Id AS nvarchar(max)) + ' , ''' + CAST(@ShopId AS nvarchar(max)) + ''' ) ';

EXEC sp_executeSQL @SQL, @ParameterDefinition, @IdParameter = @Id, @Name=@Name;