开发者

Create a DATABASE using as a Name from a Variable

开发者 https://www.devze.com 2023-01-10 13:55 出处:网络
I would like create a database using value from a variable.Here my script but it does not work. Any ideas?

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 @DataB开发者_如何学PythonaseName char(64);
SET @DataBaseName = 'DbCmsWebsiteTest';

-- Create Data Base
CREATE DATABASE @DataBaseName;
GO


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


Actually, the recommended approach is the sp_executesql function.

Here's an example of using it:

DECLARE @SqlCommand NVARCHAR(255), @DatabaseName NVARCHAR(63)
SET @DatabaseName = 'DbName'
SET @SqlCommand = N'CREATE DATABASE ' + @DatabaseName
EXECUTE sp_executesql @SqlCommand
0

精彩评论

暂无评论...
验证码 换一张
取 消