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
精彩评论