Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Create Dabase object from a script of a database c

Author  Topic 

kamii47
Constraint Violating Yak Guru

353 Posts

Posted - 2010-04-13 : 14:19:30
I am creating database via dynamic sql.Now what i wanted is that the database objects should also be created in the same run.

I am current trying with

DECLARE @SQL VARCHAR(MAX)
DECLARE @DBName VARCHAR(20)
DECLARE @DBPath VARCHAR(255)

SET @DBName = 'TestMA'
SET @DBPath = 'E:\SQLData\' -- here i wanted the default database path



SET @SQL = '
CREATE DATABASE ' + @DBName + '
ON
PRIMARY
(NAME = ' + @DBName + ',
FILENAME = '''+ @DBPath + @DBName + '.mdf'',
SIZE = 50MB,
FILEGROWTH = 10%),'

Set @SQL = @SQL + '
FILEGROUP [MA_CLUSTERINDEX]
(NAME = MA_CLUSTERINDEX,
FILENAME = '''+ @DBPath + @DBName + '_1.ndf'',
SIZE = 1MB,
FILEGROWTH = 10%),'

Set @SQL = @SQL + '
FILEGROUP [MA_NONCLUSTERINDEX]
(NAME = MA_NONCLUSTERINDEX,
FILENAME = '''+ @DBPath + @DBName + '_2.ndf'',
SIZE = 1MB,
FILEGROWTH = 10%),'

Set @SQL = @SQL + '
FILEGROUP [MA_IMR]
(NAME = MA_IMR,
FILENAME = '''+ @DBPath + @DBName + '_5.ndf'',
SIZE = 1MB,
FILEGROWTH = 10%);'



EXEC (@SQL)


After creation of my DB i have to run the script to create tables/stored procedures and other DB objects

I am getting error at USE [TestMA]
I even have to add some initial record in the tables
I don't wanted to have different script file.

Kamran Shahid
Sr. Software Engineer
(MCSD.Net,MCPD.net)

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-04-13 : 14:58:40
Instead of code like this for the database objects, you should instead put all of your objects in a file and then specify the database name via osql.exe.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page
   

- Advertisement -