1

While creating Windows Azura SQL database, this script will be available to you.

The script shown below is supposed to prevent possible collisions that occurs when two tables have exactly the same name.

My question is: Can anyone explain in details how this code works Note: I have a good background of Databases and using of SQL

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Department]') AND type in (N'U'))

1 Answer 1

1

sys.objects - MSDN:

Contains a row for each user-defined, schema-scoped object that is created within a database.

sys.objects.type:

U = Table (user-defined)

OBJECT_ID - MSDN:

Returns the database object identification number of a schema-scoped object.

Hence, you query for the existence of the object id returned by passing an object name to the OBJECT_ID function specifying that the type should be a table.

If it does not exist, it wouldn't return any rows and thus not satisfy the condition in your wrapping statement : IF NOT EXISTS

Sign up to request clarification or add additional context in comments.

3 Comments

And most likely, SQL Azure would also support sys.tables which is focused on tables (then you don't need to specify the type of the object anymore - that's a given by nature of the catalog view you're looking at)
Ok thanks but what does the letter N in "type in (N'U')" mean ?
As listed above. type = u means user defined table. The N is just there for nvarchar if I remember correctly.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.