Home > Database > Mysql Tutorial > How Can I Dynamically Create SQL Logins with Variable Usernames?

How Can I Dynamically Create SQL Logins with Variable Usernames?

Linda Hamilton
Release: 2024-12-18 07:36:14
Original
256 people have browsed it

How Can I Dynamically Create SQL Logins with Variable Usernames?

Unable to Create LOGIN with Variable Username

Justin, a developer seeking assistance in creating a stored procedure, faces the challenge of establishing a SQL login for tenants. However, his initial attempt using parameters results in the following errors:

  • Incorrect syntax near '@username'
  • Incorrect syntax near the keyword 'with'

Solution

CREATE LOGIN, unfortunately, does not allow the use of variables. A workaround is to embed the login creation statement in a dynamic SQL string:

DECLARE @sql nvarchar(max) = 'CREATE LOGIN ' + quotename(@username) + ' WITH PASSWORD = ' + quotename(@password, '''');
EXEC(@sql);
Copy after login

Note: Quotename is added for protection against SQL injection attacks.

The above is the detailed content of How Can I Dynamically Create SQL Logins with Variable Usernames?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template