Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SCHEMA_NAME() returns NULL

I am using the SCHEMA_NAME() function in a a T-SQL script.

It returns NULL for me, but the default schema for my colleague.

The documentation for SCHEMA_NAME() only lists NULL as a possible value when one also supplies an argument to the SCHEMA_NAME() function.

Here is the documentation for SCHEMA_NAME(): https://learn.microsoft.com/en-us/sql/t-sql/functions/schema-name-transact-sql

What should I look for when debugging this problem?

The DBA has checked that my permissions are same for my colleague and myself.

I am calling the function without any arguments so the documentation's stated case of returning NULL when schema_id is not valid does not apply -- at least not explicitly.

The DBA confirmed I have a default schema and I used the following select to confirm I have a default schema:

select * from sys.database_principles dp where dp.name = USER_NAME();

The DBA changed my default schema to something else, then changed it back in case there is something set in the background.

This happens in SQL Studio and when I run on the command line using sqlcmd.

I have noticed that when I run CREATE PROCEDURE myproc the procedure is created in my default schema, but when I run execute myproc I need to do execute myschema.myproc. That is: I must specify the schema.

I have verified that the default schema exists by hard coding the schema name in the call to the stored procedure.

like image 625
Be Kind To New Users Avatar asked Sep 26 '26 05:09

Be Kind To New Users


2 Answers

This can also happen when you are performing query on a different database than the schema_id

e.g.

select sn = schema_name(schema_id) from [yourdbname].sys.all_objects 

and the current database is not [yourdbname]

like image 161
PockyMaster Avatar answered Sep 27 '26 18:09

PockyMaster


I was also facing the same issue with Schema_name() return null value but sys.database_principal showing default schema as my user name,Then I noticed that schema(username) was deleted by DBA team. When they recreate the same schema. My issue got resolved. You can check the list of schema in database using sys.schemas.

like image 38
Nitika Avatar answered Sep 27 '26 20:09

Nitika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!