SQL Server需要标量变量声明

时间:2017-03-18 10:34:58

标签: sql sql-server

我在Management Studio中有以下SQL代码来创建存储过程。尝试执行查询时,收到错误消息:

  

必须声明标量变量“@Id”

但我已经宣布@Id - 可能是什么问题?

我的代码:

CREATE PROCEDURE [dbo].[DecryptMyName]  
     (@Id Int,
      @MyName varbinary(MAX))
AS
GO
OPEN SYMMETRIC KEY SymmetricKeyxx
DECRYPTION BY CERTIFICATE Certificatexx;
GO
-- Now list the original ID, the encrypted ID 
SELECT CONVERT(nvarchar, DecryptByKey(MyName)) 
FROM dbo.MyTable WHERE Id=@Id ;

 -- Close the symmetric key
CLOSE SYMMETRIC KEY SymmetricKeyxx;
GO

2 个答案:

答案 0 :(得分:1)

存储过程正文中不允许

GO。我建议您始终将正文括在BEGIN / END中以避免此问题。

这有用吗?

CREATE PROCEDURE [dbo].[DecryptMyName]  (
    @Id Int ,
    @MyName varbinary(MAX)
) AS
BEGIN
    OPEN SYMMETRIC KEY SymmetricKeyxx
    DECRYPTION BY CERTIFICATE Certificatexx;

    -- Now list the original ID, the encrypted ID 
    SELECT CONVERT(nvarchar, DecryptByKey(MyName)) 
    FROM dbo.MyTable WHERE Id=@Id ;

     -- Close the symmetric key
    CLOSE SYMMETRIC KEY SymmetricKeyxx;

END;

如果没有,则需要使用动态SQL。

答案 1 :(得分:0)

只需在查询中删除“开始”字样即可生效

这样:

    CREATE PROCEDURE [dbo].[DecryptMyName]  
         (@Id Int,
          @MyName varbinary(MAX))
    AS

    OPEN SYMMETRIC KEY SymmetricKeyxx
    DECRYPTION BY CERTIFICATE Certificatexx;

    -- Now list the original ID, the encrypted ID 
    SELECT CONVERT(nvarchar, DecryptByKey(MyName)) 
    FROM dbo.MyTable WHERE Id=@Id ;

     -- Close the symmetric key
    CLOSE SYMMETRIC KEY SymmetricKeyxx;

对于最佳实践,请始终对存储过程使用BEGIN和END语句 像这样:

    CREATE PROCEDURE [dbo].[DecryptMyName]  
         (@Id Int,
          @MyName varbinary(MAX))
    AS
    BEGIN
    OPEN SYMMETRIC KEY SymmetricKeyxx
    DECRYPTION BY CERTIFICATE Certificatexx;

    -- Now list the original ID, the encrypted ID 
    SELECT CONVERT(nvarchar, DecryptByKey(MyName)) 
    FROM dbo.MyTable WHERE Id=@Id ;

     -- Close the symmetric key
    CLOSE SYMMETRIC KEY SymmetricKeyxx;
    END