星期四, 8月 28, 2014

建立 MS SQL 資料庫,或當已存在時打掉重建

DECLARE @Database sysname;
DECLARE @Collate varchar(MAX);
SET @Database = 'Your_Database_Name';
SET @Collate = 'Chinese_Taiwan_Stroke_Bin';

IF (@Database LIKE '%[^0-9A-Z_]%')
    RAISERROR('Invalid Characters in Name, %s', 16, 1, @Database);
ELSE
    DECLARE @Quote varchar(MAX);
    SET @Quote = QUOTENAME(@Database);
    USE master;
    IF EXISTS (SELECT * FROM sys.databases WHERE Name = @Database)
        BEGIN
            EXEC('ALTER DATABASE ' + @Quote + ' SET SINGLE_USER WITH ROLLBACK IMMEDIATE');
            EXEC('DROP DATABASE ' + @Quote);
        END
    EXEC('CREATE DATABASE ' + @Quote + ' COLLATE ' + @Collate);
    EXEC('ALTER DATABASE ' + @Quote + ' SET MULTI_USER WITH ROLLBACK IMMEDIATE');

沒有留言:

張貼留言