执行SQL Server存储过程时的语法错误

时间:2018-12-24 08:13:22

标签: sql sql-server

ALTER PROCEDURE dbo.encrypt 
    @columnname NVARCHAR(100), 
    @TblName NVARCHAR(200) 
WITH ENCRYPTION 
AS 
BEGIN 
    SET NOCOUNT ON; 

    DECLARE @encryptcolumn NVARCHAR(200); 
    DECLARE @AlterQuery NVARCHAR(200);
    DECLARE @TblName NVARCHAR(200); 

    OPEN SYMMETRIC KEY Password_Key DECRYPTION BY CERTIFICATE PasswordCertificate;
    SET @encryptcolumn = (@columnname + 'encrypt');

    IF @encryptcolumn IS NOT NULL
        SET @AlterQuery = 'ALTER TABLE ['+@TblName+'] add  ['+@encryptcolumn+'] varbinary(max)null);' 

        EXEC sp_executesql @AlterQuery; 

        UPDATE @TblName 
        SET @encryptcolumn = ENCRYPTBYKEY(KEY_GUID('datamartSymKey'), CONVERT(varbinary, @columnname)) 
    END 
GO

当我尝试执行此操作时,会引发此错误:

  

变量名称'@TblName'已被声明。变量名称在查询批处理或存储过程中必须唯一。

1 个答案:

答案 0 :(得分:2)

出现此错误是因为您已在过程中通过了@tblName。您可以通过删除声明并将值通过过程调用传递来解决此问题。

除此之外,您还必须使用EXEC来运行更新查询,因为您的表名可能会更改。

ALTER PROCEDURE dbo.encrypt @columnname nvarchar(100), @TblName nvarchar(200) WITH ENCRYPTION AS BEGIN SET NOCOUNT ON; 
    DECLARE @encryptcolumn nvarchar(200); 
    DECLARE @AlterQuery nvarchar(200);

    OPEN SYMMETRIC KEY Password_Key DECRYPTION BY CERTIFICATE PasswordCertificate;
    set @encryptcolumn=(@columnname + 'encrypt');
    if @encryptcolumn is not null 
        SET @AlterQuery='ALTER TABLE ['+@TblName+'] add  ['+@encryptcolumn+'] varbinary(max)null);' 
        exec sp_executesql @AlterQuery; 

        DECLARE @sqlCommand varchar(1000)
        SET @sqlCommand = 'UPDATE ' +@TblName + ' SET ' + @encryptcolumn + ' = ENCRYPTBYKEY(KEY_GUID(''datamartSymKey''),CONVERT(varbinary, ' + @columnname + '))'
        EXEC (@sqlCommand)
    END 
GO