Monday, March 26, 2012

problem in creating database and table in one shot

I need to create a database and then create tables in it..

IF EXISTS (SELECT name FROM sys.databases WHERE name = N'DB1')
DROP DATABASE [DB1]

-- create a new database
CREATE DATABASE [DB1] ON PRIMARY
( NAME = N'DB1', FILENAME = N'D:\DB1.mdf' ,
SIZE = 51200KB , MAXSIZE = UNLIMITED, FILEGROWTH = 30720KB )
LOG ON
( NAME = N'DB1_log', FILENAME = N'D:\DB1_log.ldf' , SIZE = 2048KB , MAXSIZE = UNLIMITED , FILEGROWTH = 30720KB )
COLLATE Latin1_General_CI_AS


CREATE TABLE [DB1].[dbo].[SALES](
[PERIOD] [int] NOT NULL,
[LOC] [nchar](3) COLLATE Latin1_General_CI_AS NOT NULL
) ON [PRIMARY]

If i run the above statement one after one, they work; however, if I run all of them together (or in sp), the following error raised:

Msg 2702, Level 16, State 2, Line 43
Database 'DB1' does not exist.

May I know how can i create a database and then immediately the tables in sp!

Thanks

use master;

go

drop database mydatabase;

go

create database mydatabase;

go

use mydatabase;

go

create table mytable(i int );

|||Thx, but it doesn't work in stored procedure.|||

HI;

EXEC('CREATE TABLE [DB1].[dbo].[SALES](
[PERIOD] [int] NOT NULL,
[LOC] [nchar](3) COLLATE Latin1_General_CI_AS NOT NULL
) ON [PRIMARY]')

HTH, Jens Suessmeyer.

http://www.sqlserver2005.de

|||thx

No comments:

Post a Comment