我正在创建一个 Visual Studio 数据库项目。
在其中一个脚本中,我想实现类似的目标
CREATE USER [$(DatabaseName)\UserX]
WITHOUT LOGIN
WITH DEFAULT_SCHEMA = dbo
哪个弹窗错误
SQL70604:对象名称中不允许使用 SqlCmd 变量引用 ($(数据库名称)\UserX).
经过一番研究,我发现最接近的解决方案是通过
sp_executesql
创建用户,但这会导致模式比较功能无效,对吗?
我对数据库项目不太熟悉,但我想应该有一些更好的方法来实现这一点,我只需要一些指导。
The error message: `"SQL70604: SqlCmd variable reference is not allowed in object names ($(DatabaseName)\UserX)"` indicates that you cannot use SqlCmd variables to dynamically construct object names (including usernames) within SQL statements.
You can use somthing like this :
> use databaseName
> CREATE USER [UserX]
> WITHOUT LOGIN
> WITH DEFAULT_SCHEMA = dbo
[db name][1]
[db query][2]
[user created][3]
But let's say, you want to dynamically construct object names (including usernames) within SQL statements.
For that you can create a SQL statement and use `sp_executesql` command:
DECLARE @sql NVARCHAR(MAX) = N'CREATE USER [YourUserName] WITHOUT LOGIN WITH DEFAULT_SCHEMA = dbo';
EXEC sp_executesql @sql, N'@DatabaseName sysname', @DatabaseName = N'yourdatabase';
[Dynamic Query Execution][4]
[1]: https://i.stack.imgur.com/qtJNZ.png
[2]: https://i.stack.imgur.com/6t4iR.png
[3]: https://i.stack.imgur.com/eXm3O.png
[4]: https://i.stack.imgur.com/ZYHiF.png