views:

30

answers:

2

Hi,

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

+1  A: 

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.

e.g

Create Procedure dbo.MySP

Barry
I am getting the error while creating the SP itself.
HotTester
@HotTester - sorry misread your question. I've updated my answer
Barry
+1... thanks for the ans
HotTester
+3  A: 

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.

Martin Smith
Thanks... this was the problem. After using dbo.spname problem was solved. :)
HotTester
Good point regarding sql injection. Are there any other things one should keep in mind using dynamic queries in context to security and speed ?
HotTester
Yes. See [The Curse and Blessings of Dynamic SQL - Dealing with Dynamic Table and Column Names](http://www.sommarskog.se/dynamic_sql.html#objectnames)
Martin Smith
Thanks for the link !
HotTester