2

I am getting the error in my sproc and I cannot figure out why. I have looked at other, almost identical questions like this Here and the answers aren't doing the trick for me. the syntax error is at the 'Go' right after the database creation.

USE [DATABASENAME]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[Sproc]
@Id int
AS
BEGIN

SET NOCOUNT ON;

IF NOT EXISTS (SELECT name FROM sys.databases WHERE name = 
N'Name')

create database Name;

GO

CREATE TABLE [Name].[dbo].[Account](
[Id] [int] IDENTITY(1,1) NOT NULL,
[AccountId] [int] NOT NULL
);
Robert
  • 33
  • 1
  • 4

1 Answers1

4

GO is not allowed in stored procedures. It separates batches and a procedure itself is one batch which cannot be separated.

You could use one procedure to create the database, then a second procedure to create the table.

Edit

Actually you could do it in one procedure:

CREATE PROCEDURE [dbo].[Sproc]
AS
BEGIN

EXEC ('USE [Master]; CREATE DATABASE [name]')
EXEC ('USE [Name]; CREATE TABLE [name].dbo.[Account] (id int)')

END
Aaron Dietz
  • 10,137
  • 1
  • 14
  • 26