sp_executesql - 参数附近的语法不正确

时间:2018-04-11 13:09:25

标签: sql sql-server

我使用带参数的查询来创建数据库用户和SQL Server登录。 我有下一个程序:

PROCEDURE [dbo].[regNewOfficial]
@name nvarchar(30),
@password nvarchar(30)
AS
DECLARE @sqlRequest NVARCHAR(1000);
SET @sqlRequest = 'CREATE LOGIN @nameP' +  
                    ' WITH PASSWORD = @passwordP' + 
                    ' , DEFAULT_DATABASE=[TreeBase]' +  
                    ' CREATE USER @nameP' + 
                    ' FOR LOGIN @nameP' +
                    ' ALTER ROLE official_role ADD MEMBER @nameP ;';
EXECUTE sp_executesql  @sqlRequest, N'@nameP nvarchar(30), @passwordP nvarchar(30)', @nameP = @name, @passwordP = @password;

我收到了这个错误:

  

" @ nameP"

附近的语法不正确

解: 在连接字符串时需要使用QUOTENAME()

使用不带QUOTENAME()的参数的结果:

  

创建登录@nameP WITH PASSWORD = @passwordP,DEFAULT_DATABASE = [TreeBase] CREATE USER @nameP FOR LOGIN @nameP ALTER ROLE official_role ADD MEMBER @nameP;

使用QUOTENAME()

  

使用PASSWORD =' bbbbb'创建登录[aaaaa] ,DEFAULT_DATABASE = [TreeBase];    创建用户[aaaaa]登录[aaaaa];    ALTER ROLE official_role ADD MEMBER [aaaaa];

1 个答案:

答案 0 :(得分:3)

CREATE LOGIN需要文字字符串才能工作;你不能传递变量。因此,您需要以不同的方式执行动态SQL。

ALTER PROCEDURE [dbo].[regNewOfficial]
    @name nvarchar(30),
    @password nvarchar(30)
AS

    DECLARE @sqlRequest NVARCHAR(1000);
    SET @sqlRequest = N'CREATE LOGIN ' + QUOTENAME(@name) +
                      N' WITH PASSWORD = ' + QUOTENAME(@password,'''') +
                      N' , DEFAULT_DATABASE=[TreeBase]' + N';' + NCHAR(10) +  
                      N' CREATE USER ' + QUOTENAME(@name) +
                      N' FOR LOGIN ' + QUOTENAME(@name) + N';' + NCHAR(10) + 
                      N' ALTER ROLE official_role ADD MEMBER ' + QUOTENAME(@name) + N';';
    PRINT @sqlRequest; --This is your friend for debugging
    EXECUTE sp_executesql @sqlRequest;
GO