Use master
GO
Declare @dbName As VARCHAR(50)
SET @dbName = 'TestDB'
CREATE DATABASE @dbName
上面的 sqlserver 是脚本给了我错误。为什么?
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '@dbName'.
Use master
GO
Declare @dbName As VARCHAR(50)
SET @dbName = 'TestDB'
CREATE DATABASE @dbName
上面的 sqlserver 是脚本给了我错误。为什么?
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '@dbName'.
您不能混合使用动态 sql 和 ddl。使用动态 sql 。试试这个代码:
Use master
GO
Declare @dbName As VARCHAR(50)
DECLARE @Q VARCHAR(MAX)
SET @dbName = 'TestDB'
SET @Q='CREATE DATABASE '+ @dbName
EXEC(@Q)
如果因为您要传递 VARCHAR 类型和创建数据库而无法工作,则它需要一个对象而不是 Varchar。否则,您需要将整个查询作为字符串传递给执行;
Declare @dbName As VARCHAR(50) = 'TestDB'
DECLARE @Creation VARCHAR(50) ='CREATE DATABASE '+ @dbName
EXEC(@Creation)