Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out default SQL Server schema for session

I have a requirement to know what the current default schema is in a SQL script that is doing some DDL. I don't need to set the schema, but I do need to get a reference to it (name or ID) into a variable. The script may be running as a windows login, so the following isn't sufficient:

SELECT name, default_schema_name  FROM sys.database_principals  WHERE type = 'S' and name = SYSTEM_USER --SYSTEM User won't be named as a principal 

I've thought of doing it by creating a randomly named object in the current schema, and then looking at its details in the information_schema, but does anyone have a tidier way?

I'm working in SQL Server 2005.

like image 285
Jon Egerton Avatar asked Apr 01 '11 12:04

Jon Egerton


People also ask

How do I select a default schema?

Set the Default Schema for a Windows Group First you need to map the login to the database by checking the Map column, then click on the Default Schema column to select the schema.

How do I change the default schema for a SQL Server user?

In that case, just use SQL Server Management Studio > Database > Security > Users > Properties and change the default schema there.

How do I select a SQL schema?

Point to your Database Name and select new query in SQLMS. Use DBNAME; Select * from [Tablename] is correct.


2 Answers

How about this.

SELECT SCHEMA_NAME()

http://msdn.microsoft.com/en-us/library/ms175068.aspx

SCHEMA_NAME will return the name of the default schema of the caller

Alternatively SCHEMA_ID()

like image 91
Chris Diver Avatar answered Sep 24 '22 14:09

Chris Diver


How about using DATABASE_PRINCIPAL_ID to get the db principal of the current user?

SELECT name, default_schema_name  FROM sys.database_principals  WHERE type = 'S' and name = USER_NAME(DATABASE_PRINCIPAL_ID()) 
like image 44
Ed Harper Avatar answered Sep 22 '22 14:09

Ed Harper