/*其实我也搞不懂为什么要用SQL来创建,明明SQL Server有图形化创建数据库多省事啊!*/
USE master;
DECLARE @sqlstr nvarchar(max)
/*定义一个变量*/
DECLARE @database_name nvarchar(20) = ‘MyDB’;
/*这里输入需要创建的数据库名*/
DECLARE @file_name_d nvarchar(200) = CONVERT(sysname, SERVERPROPERTY(‘InstanceDefaultDataPath’))
/*这里是利用SQL Server的serverproperty这个函数来获取当前实例的默认数据文件位置和日志文件位置*/
DECLARE @file_name_l nvarchar(200) = CONVERT(sysname, SERVERPROPERTY(‘InstanceDefaultLogPath’))
/*微软官方参数介绍https://docs.microsoft.com/en-us/sql/t-sql/functions/serverproperty-transact-sql?view=sql-server-2017*/
IF DB_ID(‘MyDB’) IS NOT NULL
BEGIN
PRINT ‘Database ‘ +@database_name+’ already exists’; –判断MyDB是否存在,存在的话就干掉,我也不知道为什么要这么写
DROP DATABASE MyDB; –还是手动删除吧,不使用脚本删除
END
ELSE
BEGIN
SET @sqlstr= ‘CREATE DATABASE’+’ ‘+@database_name+’ ‘
SET @sqlstr = @sqlstr +’ON’
SET @sqlstr = @sqlstr +'(‘
SET @sqlstr = @sqlstr +’NAME = ‘+’ ‘+@database_name+’_dat,’
SET @sqlstr = @sqlstr +’FILENAME = ‘+””+@file_name_d+”+@database_name+’.mdf”,’
SET @sqlstr = @sqlstr +’SIZE = 10,’
SET @sqlstr = @sqlstr +’MAXSIZE = 50,’
SET @sqlstr = @sqlstr +’FILEGROWTH = 5′
SET @sqlstr = @sqlstr +’)’
SET @sqlstr = @sqlstr +’LOG ON’
SET @sqlstr = @sqlstr +'( NAME = ‘+’ ‘+@database_name+’_log,’
SET @sqlstr = @sqlstr +’FILENAME = ‘+””+@file_name_l+”+@database_name+’.ldf”,’
SET @sqlstr = @sqlstr +’SIZE = 5MB,’
SET @sqlstr = @sqlstr +’MAXSIZE = 25MB,’
SET @sqlstr = @sqlstr +’FILEGROWTH = 5MB’
SET @sqlstr = @sqlstr +’);’
Print (@sqlstr) — 如果不想直接执行,使用使用print参数先把命令打印出来
–exec (@sqlstr); — 执行直接上面生成的动态SQL
–Print ‘Datbaase ‘+@database_name +’ has been created using default data and log location in the server configuration!!’
/*打印已经创建成功的数据库名字*/
–Print ‘Data file location = ‘+@file_name_d+@database_name+’.mdf’;
/*打印创建的数据库的数据文件路径*/
–Print ‘Log file location = ‘+@file_name_l+@database_name+’.ldf’;
/*打印创建的数据库的日志文件路径*/
END