6

I want to write a TSQL stored procedure that creates a database with a specified name, and pre-populates it with some schema.

So I use lots of EXEC statements:

EXEC('CREATE TABLE ' + @dbName + '.dbo.MyTable (...)');

etc, along with some CREATE PROCEDURE, CREATE FUNCTION etc. However, the problem comes from when I want to create a type, as CREATE TYPE statements can't have the database specified, and you can't have USE @dbName within the stored procedure.

How can I create a type in another database in a stored procedure?

4
  • 3
    Why do you want to create a database and schema inside a stored proc??? That seems a bit odd - typically, DML statements should not be executed from within stored proc - you execute those once to set up your environment, and then be done with it..
    – marc_s
    Jan 10, 2012 at 16:39
  • 1
    I want to create an arbitary number of databases depending on the input for our application (one database per customer)
    – thecoop
    Jan 10, 2012 at 16:57
  • 1
    Create the db back it up, then restore it with a new logical name and file name each time you want to add one. Jan 10, 2012 at 17:00
  • 2
    I would personally find another way to provision databases and their schema - something like a tool that generates (and possibly executes) the necessary T-SQL scripts - but I would not do this inside a stored procedure...
    – marc_s
    Jan 10, 2012 at 17:06

3 Answers 3

8

There are certain commands that can't use used as ssarabando suggests, among them is CREATE SCHEMA, which throws Msg 111 when used in with that technique.

The work around is to nest dynamic SQL blocks as follows:

exec('use tempdb; exec sp_executesql N''create schema test'' ')

The outer block does nothing except change the database, so that the inner block has the correct context when it is executed.

Notice that the inner parameter to sp_executesql needs two single quotes.

-1

You may want to take a look at sp_addtype instead. You can execute this in the database you want.

-1

You could also use this, for example:

EXEC('use ' + @dbName + ';create type somename from int not null;')

That'll select the correct database before creating the type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.