简体   繁体   中英

Facing error of "The default schema does not exist." when executing runtime query inside sp using exec()

i have made a runtime query inside a sp and am exceuting the query within the sp using exec(), but when creating the sp i am getting the error

The default schema does not exist.

The SP is:

CREATE PROCEDURE MySP
    @tableName varchar(100)

AS
BEGIN   
    SET NOCOUNT ON;

declare @selectQuery varchar(MAX)

set @selectQuery = 'select * from ' + @tableName

exec(@selectQuery)

end

kindly help

Use CREATE PROCEDURE dbo.MySP

The user you are logged in as must have a non existent default schema.

DEFAULT_SCHEMA can be set to a schema that does not currently exist in the database.

Also you should use quotename(@tableName) and a parameter type of sysname rather than varchar(100) to avoid SQL injection or just errors from non standard object names.

You could change your default schema:

ALTER USER [YOURDOMAIN\HotTester] WITH DEFAULT_SCHEMA=[dbo]
GO

then avoiding having to include [dbo]. in the CREATE PROCEDURE

It is probably because the default schema associated with the User creating the SP no longer exists or the user no longer has access to the schema.

Although, I thought SQL Server defaulted to the dbo schema. Maybe try to qualify the schema for the Stored Proc.

eg

Create Procedure dbo.MySP

I ran into this "The default schema does not exist" error on an INSERT statement. It didn't help to prefix it with the dbo schema even though the table was in the dbo schema.

The default schema for this user was a custom one. It did exist, and the user could query a table inside it.

I finally figured out that I had to add a schema with that same name in tempdb. I don't really understand why this was needed, but hopefully it will help someone else who searches for this error message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM