How to create a database using T SQL script on a specified location? Let's say, I want to create a SQL server database on D:\temp\dbFolder. How to do this?
When you create the new database you specify the location. For example:
USE [master]
GO
CREATE DATABASE [AdventureWorks] ON PRIMARY
( NAME = N'AdventureWorks_Data', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\AdventureWorks_Data.mdf' , SIZE = 167872KB , MAXSIZE = UNLIMITED, FILEGROWTH = 16384KB )
LOG ON
( NAME = N'AdventureWorks_Log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\AdventureWorks_Log.ldf' , SIZE = 2048KB , MAXSIZE = 2048GB , FILEGROWTH = 16384KB )
GO
From the SQL Server Books an example where database filenames are explicitely defined:
USE master
GO
CREATE DATABASE Sales
ON
( NAME = Sales_dat,
FILENAME = 'c:\program files\microsoft sql server\mssql\data\saledat.mdf',
SIZE = 10,
MAXSIZE = 50,
FILEGROWTH = 5 )
LOG ON
( NAME = 'Sales_log',
FILENAME = 'c:\program files\microsoft sql server\mssql\data\salelog.ldf',
SIZE = 5MB,
MAXSIZE = 25MB,
FILEGROWTH = 5MB )
GO
Create folder on your file system: D:\temp\dbFolder\
Run the script:
USE master;
GO
CREATE DATABASE TestDB1
ON ( NAME = Sales_dat, FILENAME = 'D:\temp\dbFolder\TestDB1.mdf')
LOG ON ( NAME = Sales_log, FILENAME = 'D:\temp\dbFolder\TestDB1.ldf');
GO
Using variables in Studio Manager expanding on the previous examples.
Create folders and subfolders.
Example: root folder E:\MSSQL\DATA
subfolders E:\MSSQL\DATA\DB and E:\MSSQL\DATA\Logs.
MKDIR "E:\MSSQL\DATA\DB"
MKDIR "E:\MSSQL\DATA\Logs"
Change Database name #DBNAME variable #Test_DB' to your 'DesiredName_DB'
Change Root folder path #DataPath 'E:\MSSQL\DATA' to your as per above created folders.
Run the below in Studio Manager
DECLARE #DBNAME VARCHAR(MAX)
DECLARE #DataPath AS NVARCHAR(MAX)
DECLARE #sql VARCHAR(MAX)
SET #DBNAME = N'Test_DB'
SET #DataPath = N'E:\MSSQL\DATA'
SELECT #sql = 'USE MASTER'
EXEC (#sql)
SELECT #sql = 'CREATE DATABASE '+ quotename(#DBNAME) + '
ON
PRIMARY
(
NAME = ''' + #DBNAME + '_DB'',
FILENAME = ''' + #DataPath + '\DB\' + #DBNAME + '.mdf'',
SIZE = 3136 KB , MAXSIZE = UNLIMITED,
FILEGROWTH = 1024 KB
)
LOG ON
(
NAME = '''+ #DBNAME + '_Log'',
FILENAME = '''+ #DataPath + '\Logs\' + #DBNAME + '_log.ldf'',
SIZE = 832KB , MAXSIZE = 2048 GB , FILEGROWTH = 10 %
)'
EXEC (#sql)
Or another variation on the above theme.
DECLARE #DBNAME VARCHAR(MAX)
DECLARE #DataFilePath AS NVARCHAR(MAX)
DECLARE #LogFilePath AS NVARCHAR(MAX)
DECLARE #sql VARCHAR(MAX)
SET #DBNAME = N'Test_DB'
SET #DataFilePath = N'E:\MSSQL\DATA\DB\'
SET #LogFilePath = N'E:\MSSQL\DATA\Logs\'
SELECT #sql = 'USE MASTER'
EXEC (#sql)
SELECT #sql = 'CREATE DATABASE '+ quotename(#DBNAME) + '
ON
PRIMARY
(
NAME = ''' + #DBNAME + '_DB'',
FILENAME = ''' + #DataFilePath + #DBNAME + '.mdf'',
SIZE = 3136 KB , MAXSIZE = UNLIMITED,
FILEGROWTH = 1024 KB
)
LOG ON
(
NAME = '''+ #DBNAME + '_Log'',
FILENAME = '''+ #LogFilePath+ #DBNAME + '_log.ldf'',
SIZE = 832KB , MAXSIZE = 2048 GB , FILEGROWTH = 10 %
)'
EXEC (#sql)
See this link : CREATE DATABASE (Transact-SQL)
CREATE DATABASE [ADestinyDb] CONTAINMENT = NONE ON PRIMARY
( NAME = N'ADestinyDb',
FILENAME = N'D:\temp\dbFolder\ADestinyDb.mdf' ,
SIZE = 3136 KB , MAXSIZE = UNLIMITED,
FILEGROWTH = 1024 KB )
LOG ON
( NAME = N'ADestinyDb_log',
FILENAME = N'D:\temp\dbFolder\_log.ldf' ,
SIZE = 832KB , MAXSIZE = 2048 GB , FILEGROWTH = 10 %)
Create folder on your file system: D:\temp\dbFolder\ and run the below script
(try 'sa' login)
USE master
CREATE DATABASE [faltu] ON PRIMARY
( NAME = N'faltu', FILENAME = N'D:\temp\dbFolder\faltu.mdf' , SIZE = 2048KB , FILEGROWTH = 1024KB )
LOG ON
( NAME = N'faltu_log', FILENAME = N'D:\temp\dbFolder\faltu_log.ldf' , SIZE = 1024KB , FILEGROWTH = 10%)
Related
I'm trying to add a file to a file group in order to create a partition in SQL Server. When I pass in a hardcoded file path to the the filename, the code works. But when I use a variable for the file path, I get an error
Incorrect syntax near #FilePath or Unexpected symbol #FilePath
This is my code:
USE StudentRepository
BEGIN
SET NOCOUNT ON;
DECLARE #FilePath NVARCHAR(MAX) = "C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLEXPRESS\MSSQL\DATA\",
#FileName NVARCHAR(MAX) = "FirstTerm2020",
#FileExt NVARCHAR(MAX) = ".NDF";
DECLARE #count INT = 0;
ALTER DATABASE StudentRepository
ADD FILE
(
NAME = 'FirstTerm2020',
FILENAME = #FilePath + #FileName + #FileExt, --Error here!
SIZE = 5MB,
MAXSIZE = 100MB,
FILEGROWTH = 5MB
)
TO FILEGROUP FirstTerm2020
END
When I pass a hardcoded file path to the filename, it works and creates the required partitions. as below
--Code omitted for brevity
FILENAME = "C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLEXPRESS\MSSQL\DATA\FirstTerm2020.NDF" --No error!
Please I need some help. How do I pass a file path as a variable?
This is how I solved the problem. I create a dynamic sql and passed the filepath variable like this.
USE StudentRepository
BEGIN
SET NOCOUNT ON;
DECLARE #FilePath NVARCHAR(MAX) = 'C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLEXPRESS\MSSQL\DATA\',
#FileName NVARCHAR(MAX) = 'SecondTerm2022',
#FileExt NVARCHAR(MAX) = '.NDF';
DECLARE #count INT = 0;
DECLARE #sql NVARCHAR(MAX) = '
ALTER DATABASE StudentRepository ADD FILEGROUP ' + #FileName + ';
ALTER DATABASE StudentRepository
ADD FILE
(
NAME = '+ #FileName + ',
FILENAME = ''' + #FilePath + #FileName + #FileExt + ''',
SIZE = 5MB,
MAXSIZE = 100MB,
FILEGROWTH = 5MB
)
TO FILEGROUP '+ #FileName
END
EXEC sp_executesql #sql
My major problem was that I was ommitting the three single quotes near #FilePath
I want to execute this query as you can see :
DECLARE #site_value INT;
SET #site_value = 1310;
WHILE #site_value <= 1396
BEGIN
ALTER DATABASE AdventureWorksDW
ADD FILE
(NAME = N'data_2002',
FILENAME = N'C:\symfadb2filegroup\data_'+#site_value+'.ndf',
SIZE = 5000MB,
MAXSIZE = 10000MB,
FILEGROWTH = 500MB)
TO FILEGROUP [Filegroup_2002]
SET #site_value = #site_value + 1;
END;
But I get this error in this part +#site_value
Msg 102, Level 15, State 1, Line 10
Incorrect syntax near '+'.
I used CONVERT and CONCAT but I get the same error.
you will need to use dynamic sql like below
set #Sql=' ALTER DATABASE AdventureWorksDW
ADD FILE
(NAME = N''data_2002''
FILENAME = N''C:\symfadb2filegroup\data_'''+cast(#site_value as varchar(4))+'.ndf'',
SIZE = 5000MB,
MAXSIZE = 10000MB,
FILEGROWTH = 500MB)
TO FILEGROUP [Filegroup_2002]'
print #Sql
total code below
DECLARE #site_value INT;
SET #site_value = 1310;
declare #Sql nvarchar(max)
WHILE #site_value <= 1396
BEGIN
set #Sql=' ALTER DATABASE AdventureWorksDW
ADD FILE
(NAME = N''data_2002''
FILENAME = N''C:\symfadb2filegroup\data_'''+cast(#site_value as varchar(4))+'.ndf'',
SIZE = 5000MB,
MAXSIZE = 10000MB,
FILEGROWTH = 500MB)
TO FILEGROUP [Filegroup_2002]'
print #Sql
exec(#sql)
SET #site_value = #site_value + 1;
END;
I used an existing database to generate a "CREATE"-Script via the MS SQL Server Management Tool. Then i replaced the string literals for the DB Name with variables. However, when i execute the script, it keeps saying "wrong syntax near #DBFullName" (the first use in 'NAME = #DBFullName ...'). I have no idea what the issue is, other than the possibility, that the use of variables is forbidden here.
DECLARE #DBNAME nvarchar(MAX);
SET #DBNAME = 'MyDataBase'
DECLARE #DBFullName text;
SET #DBFullName = 'MySuperDataBase';
DECLARE #DBFileName text;
SET #DBFileName = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.DEVELOPMENT\MSSQL\DATA\\' + #DBName + '.mdf';
DECLARE #DBLogName text;
SET #DBLogName = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.DEVELOPMENT\MSSQL\DATA\\' + #DBName + '.ldf';
CREATE DATABASE [#DBNAME] ON PRIMARY
( NAME = #DBFullName + '_Data', FILENAME = #DBFileName , SIZE = 30720KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10%)
LOG ON
( NAME = #DBFullName + '_Log', FILENAME = #DBLogName , SIZE = 2048KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10%)
GO
You have to use dynamic SQL. Also, you need to replace text with nvarchar(max) otherwise text concatenation won't work.
Here is full script for you:
DECLARE #DBNAME sysname;
SET #DBNAME = 'MyDataBase'
DECLARE #DBFullName sysname;
SET #DBFullName = 'MySuperDataBase';
DECLARE #DBFileName nvarchar(max);
SET #DBFileName = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.DEVELOPMENT\MSSQL\DATA\' + #DBName + '.mdf';
DECLARE #DBLogName nvarchar(max);
SET #DBLogName = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.DEVELOPMENT\MSSQL\DATA\' + #DBName + '.ldf';
DECLARE #SQL nvarchar(max);
SET #SQL = N'
CREATE DATABASE ' + QUOTENAME(#DBNAME) + ' ON PRIMARY
(NAME = ' + QUOTENAME(#DBFullName + '_Data') + ',
FILENAME = ' + QUOTENAME(#DBFileName, '''') + ',
SIZE = 30720KB,
MAXSIZE = UNLIMITED,
FILEGROWTH = 10%)
LOG ON (
NAME = ' + QUOTENAME(#DBFullName + '_Log') + ',
FILENAME = ' + QUOTENAME(#DBLogName, '''') + ',
SIZE = 2048KB,
MAXSIZE = UNLIMITED,
FILEGROWTH = 10%)'
PRINT #SQL
EXEC (#SQL)
GO
Works on my machine! :)
I have simple code
: CREATE DATABASE [asst]
: ON (NAME = 'asst_dat', FILENAME = 'C:\data' , SIZE = 62, FILEGROWTH = 10%)
: LOG ON (NAME = 'asst_log', FILENAME = 'C:\data' , SIZE = 146, FILEGROWTH = 10%)
How can I change the FILENAME parameter to create DB in the default installation path like C:\Program Files\Microsoft SQL Server\MSSQL10_50.ATASSIST\MSSQL. So why I need it: from version to version, from instance to instance of SQL Server this locations differs
First create the database and then alter file properties as needed.
CREATE DATABASE [DBName]
GO
ALTER DATABASE [DBName] MODIFY FILE
( NAME = N'DBName' , SIZE = 512MB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
GO
ALTER DATABASE [DBName] MODIFY FILE
( NAME = N'DBName_log' , SIZE = 256MB , MAXSIZE = UNLIMITED , FILEGROWTH = 10%)
GO
You can use the following variables, that respectively contain the root directory of your install and the data directory :
SELECT ##basedir, ##datadir;
Thanks, überjesus, I've simplified your code a little bit
DECLARE #rows varchar(MAX),
#script nvarchar(MAX);
SET #rows = (SELECT physical_name AS current_file_location
FROM sys.master_files
where name = 'master');
SET #rows = Replace(#rows, 'master.mdf', '')
SELECT #rows;
set #script = 'CREATE DATABASE [assist1]
ON (NAME = ''asst_dat'', FILENAME = ''' + #rows + 'assist1.mdf'' , SIZE = 62, FILEGROWTH = 10%)
LOG ON (NAME = ''asst_log'', FILENAME = ''' + #rows + 'assist1_log.ldf'' , SIZE = 146, FILEGROWTH = 10%);'
exec(#script);
Thanks for a great idea!
try this
You can create a database without specifying file details, like:
CREATE DATABASE DatabaseName;
Assuming you are using SQL Server 2005 or 2008 this should do it. Although it's probably a bit longer than you expected :-) You could put the main part of the code into a function and call that every time you need to create a database.
declare #instance_name nvarchar(200),
#system_instance_name nvarchar(200),
#registry_key nvarchar(512),
#path_data nvarchar(260),
#path_log nvarchar(260),
#value_name nvarchar(20),
#script nvarchar(4000);
set #instance_name = coalesce(convert(nvarchar(20), serverproperty('InstanceName')), 'MSSQLSERVER');
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\Microsoft SQL Server\Instance Names\SQL', #instance_name, #system_instance_name output;
set #registry_key = N'Software\Microsoft\Microsoft SQL Server\' + #system_instance_name + '\MSSQLServer';
/* determine default location for data files */
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', #registry_key, N'DefaultData', #path_data output;
if #path_data is null
begin
/* this is only executed if we are using the default instance */
set #registry_key = N'Software\Microsoft\Microsoft SQL Server\' + #system_instance_name + '\Setup';
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', #registry_key, N'SQLDataRoot', #path_data output;
set #path_data = #path_data + '\Data';
end;
/* determine default location for log files */
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', #registry_key, N'DefaultLog', #path_log output;
if #path_log is null
begin
/* this is only executed if we are using the default instance */
set #registry_key = N'Software\Microsoft\Microsoft SQL Server\' + #system_instance_name + '\Setup';
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', #registry_key, N'SQLDataRoot', #path_log output;
set #path_log = #path_log + '\Data';
end;
set #script = 'CREATE DATABASE [asst]
ON (NAME = ''asst_dat'', FILENAME = ''' + #path_data + '\yourfile.mdf'' , SIZE = 62, FILEGROWTH = 10%)
LOG ON (NAME = ''asst_log'', FILENAME = ''' + #path_log + '\yourfile.ldf'' , SIZE = 146, FILEGROWTH = 10%);'
exec(#script);
You can not use variables in the CREATE DABASE statement. That's why you have to create a variable that holds the command and execute that as a script.
I have written the following procedure to create a series of 20 databases.
But it is not creating them. The database is not created even when I go to my H: drive and didnot find the ldf and mdf named bharath1 bharath2 like...
What did I do wrong with this?
USE master
GO
DECLARE #command varchar(1000), #i int
while #i < 5
SET #command = 'CREATE DATABASE Bharath' + CAST(#i AS varchar) + '
ON ( NAME = ''Bharath_dat'',
FILENAME = ''H:\MSSQL10.MSSQLSERVER\MSSQL10.MSSQLSERVER\MSSQL\DATA\Bharath' +
CAST(#i AS varchar) + '.mdf'', SIZE = 10, MAXSIZE = 50, FILEGROWTH = 5 )
LOG ON ( NAME = ''Bharath_log'',
FILENAME = ''H:\MSSQL10.MSSQLSERVER\MSSQL10.MSSQLSERVER\MSSQL\DATA\Bharath' +
CAST(#i AS varchar) + '.ldf'', SIZE = 5MB, MAXSIZE = 25MB, FILEGROWTH = 5MB )'
EXEC (#command)
SET #i = #i + 1
GO
I don't have any idea in SQL Server stored procedure as of my knowledge and with somebody support i did like this. But i am not finding any databases.
Any help greatly appreciated.
OK, I don't see the BEGIN and END block right after the WHILE loop which may cause SQL to do an endless loop to run a SET #command statement only.
You need to enclose the WHILE with BEGIN and END...
DECLARE #command as varchar(1000), #i int
SET #i = 0
WHILE #i < 5
BEGIN
SET #command = 'CREATE DATABASE Example' + CAST(#i AS varchar)
EXEC(#command)
SET #i = #i + 1
END
This works for me. (SET #i = 0 is a must)
YOu need to initialise #i, add this after your declare:
SET #i = 1
There's a few things you've missed - you first of all need to put your several SQL command that you want to execute over and over again into a BEGIN......END block.
Second, you need to initialize your #i counter! Otherwise, it'll never get into that WHILE loop in the first place.
And thirdly, your CREATE DATABASE call was wrong - you need to specify a filegroup where to create the database (CREATE DATABASE (name) ON (filegroup) .......).
Here's my code:
USE master
GO
DECLARE #command varchar(1000), #instanceName VARCHAR(100), #i int
SET #i = 1
WHILE #i <= 5
BEGIN
SET #instanceName = 'Bharath' + CAST(#i AS VARCHAR(10))
SET #command = 'CREATE DATABASE ' + #instanceName +
' ON PRIMARY ( NAME = N''' + #instanceName + ''', ' +
'FILENAME = ''H:\MSSQL10.MSSQLSERVER\MSSQL10.MSSQLSERVER\MSSQL\DATA\' +
#instanceName + '.mdf'', SIZE = 10, MAXSIZE = 50, FILEGROWTH = 5 ) ' +
'LOG ON ( NAME = N''' + #instanceName + '_LOG'', ' +
'FILENAME = ''H:\MSSQL10.MSSQLSERVER\MSSQL10.MSSQLSERVER\MSSQL\DATA\' +
#instanceName + '.ldf'', SIZE = 5MB, MAXSIZE = 25MB, FILEGROWTH = 5MB )'
EXEC (#command)
SET #i = #i + 1
END
GO