1

How can I do something like this:

Create Database mydb;
Create Table mydb.dbo.Customers
(
ID int,
FirstName varchar(255),
LastName varchar(255),
);

in a single sql script in SQL server managment studio ? It gives me the message Database 'mydb' does not exist.

1

Edit: use mydb; after creating the database, doesn't seem to work.

dimitris93
  • 4,155
  • 11
  • 50
  • 86

2 Answers2

2

use this command immediately after creating database (with go):

...
go
use myDb
go
void
  • 7,760
  • 3
  • 25
  • 43
  • http://i.gyazo.com/739054205aae7c46b3c2be75bb79cf72.png this is the error i got with your code, `Database 'mydb' does not exist. Make sure that the name is entered correctly.` – dimitris93 Mar 22 '15 at 01:50
  • Ok, just let me to review it – void Mar 22 '15 at 01:53
  • @Shiro, sorry I was in hurry and didn't notice you missed the `go` keywod, answer editted – void Mar 22 '15 at 01:58
  • it seems that `Create Database mydb; GO CREATE Table.....` works as well (just using 1 `go`) . do you find that a better solution ? it seems like `go` works as a batch separator, (http://stackoverflow.com/questions/2299249/what-is-the-use-of-go-in-sql-server-management-studio) i think this works well – dimitris93 Mar 22 '15 at 01:58
  • what do you mean better solution? you mean for create database!? of course it's better to specify some other parameters like, file location, size, maxsize, etc, see [here](https://msdn.microsoft.com/en-us/library/ms176061.aspx) – void Mar 22 '15 at 02:01
  • No i mean that it is 2 lines less code this way. `Create Database mydb; GO CREATE Table...` **vs** `Create Database mydb; Go use mydb; Go CREATE Table...` – dimitris93 Mar 22 '15 at 02:03
  • I'm not sure but I think you can change the `GO` to `;`, it's just a terminator – void Mar 22 '15 at 02:04
1

This worked for me:

CREATE DATABASE mydb;
GO
USE mydb;
GO
CREATE TABLE mydb.dbo.Customers
    (
      ID INT ,
      FirstName VARCHAR(255) ,
      LastName VARCHAR(255),
    );
Icarus
  • 63,293
  • 14
  • 100
  • 115
  • it seems that `Create Database mydb; GO CREATE Table.....` works as well. do you find that a better solution ? – dimitris93 Mar 22 '15 at 01:57
  • 1
    @Shiro I wouldn't particularly care either version but keep in mind that the `GO` keyword is something that only works in SSMS. You cannot use the `GO` keyword within your application code, for example. – Icarus Mar 22 '15 at 02:00