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
When I try to execute this, it's throwing this error:
The variable name '@TblName' has already been declared. Variable names must be unique within a query batch or stored procedure.
@TblNameis already a parameter but you try to (re)declare it in the procedure body,@AlterQueryjust the line before, not just try to pass the table name as a variable. The syntax you're using requires@TblNameto be a table variable.EXECinstead ofsp_executesql) Can't test it, but should do the same thing.