Blog Post

CREATE SCHEMA can do what?!?!?

,

So I was studying for the 70-451 and ended up reading the BOL entry for CREATE SCHEMA. I honestly can’t remember why, but what I do remember is thinking “CREATE SCHEMA can do what?!?!?” but with maybe a few more exclamation points.

Now I had always thought that CREATE SCHEMA did just that, created a schema. I mean I knew it had the option to specify the owner. Use the keyword AUTHORIZATION in case you were wondering. But that was it. I mean what else was there going to be?

CREATE SCHEMA MySchema AUTHORIZATION MySchemaOwner

Seems simple enough right? I couldn’t think of anything else that might have been added. But there was just a little bit more.

Would you believe this not only works but is a single command?

CREATE SCHEMA MySchema 
-- Set up the owner of the schema
AUTHORIZATION MySchemaOwner
-- Create a table within the schema
CREATE TABLE MyTable (Id INT, MyString varchar(20))
-- Create a table not within the schema
CREATE TABLE dbo.MyTable2 (Id INT, MyString varchar(20))
-- Create a view within the schema
CREATE VIEW MyView AS SELECT * FROM dbo.MyTable
-- Create a view not within the schema
CREATE VIEW dbo.MyView2 AS SELECT * FROM MySchema.MyTable
-- Grant/Deny/Revoke permissions to objects within the schema
GRANT SELECT ON MyView to guest
-- Grant/Deny/Revoke permissions to objects not within the schema
GRANT SELECT ON MyTable2 TO guest
GO

I have no idea why it was set up this way. Maybe so that you could create tables and views and grant permissions all in the same batch as creating the schema itself. Since the CREATE SCHEMA command has to be the only command in a batch.

Quick note on something I found while creating my sample script, the schema being created is the default schema for any object created while in the command. It’s also the default schema for a GRANT/DENY/REVOKE statements performed in the command. And just to make things more fun, during the GRANT/DENY/REVOKE commands it will also find objects owned by the DBO schema when using a single part name. I believe it looks for the schema being created first then searches through the DBO schema, but I haven’t gotten around to testing it yet.

I’m still somewhat surprised by the scope of it though. A single command that could create a schema, create dozens, or more, tables and views, and then grant/deny the permissions for the entire database. Absolutely amazing.

Filed under: Microsoft SQL Server, SQLServerPedia Syndication, T-SQL Tagged: code language, language sql, microsoft sql server, sql statements, T-SQL

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating