使用变量中的名称创建数据库
我想使用变量中的值创建一个数据库.这是我的脚本,但它不起作用.有任何想法吗?
I would like create a database using value from a variable. Here my script but it does not work. Any ideas?
-- Set Data Base name
DECLARE @DataBaseName char(64);
SET @DataBaseName = 'DbCmsWebsiteTest';
-- Create Data Base
CREATE DATABASE @DataBaseName;
GO
推荐答案
我认为您需要动态 SQL(如果名称是用户提供的,则需要采取适当的预防措施)
You'd need dynamic SQL for this I think (with appropriate precautions if the name is user supplied)
-- Set Data Base name
DECLARE @DataBaseName sysname;
SET @DataBaseName = 'DbCmsWebsiteTest';
IF (@DataBaseName LIKE '%[^0-9A-Z]%')
RAISERROR('Invalid Characters in Name, %s',16,1,@DataBaseName)
ELSE
BEGIN
SET @DataBaseName = QUOTENAME(@DataBaseName)
EXEC('CREATE DATABASE '+ @DataBaseName)
END
相关文章