Saturday, August 5, 2023

C# SMO: Unable to get objects by name but able to get by index

Replicating Issue

StoredProcedure sp = db.StoredProcedures["spName"]; // Returns null

Does not return the same as 
StoredProcedure sp = db.StoredProcedures[0]; // Returns object


If I traverse the array (technically a collection), I will find spName. Even if I do:
StoredProcedure sp = db.StoredProcedures[0]; // Returns object
StoredProcedure spByName = db.StoredProcedures[sp.Name]; // returns null


Possible Solution

First I tried. https://www.tek-tips.com/viewthread.cfm?qid=1736324
StoredProcedure storedProcedure =
db.StoredProcedures.Cast<StoredProcedure>().SingleOrDefault(sp => sp.Schema == "YourSchemaName" && sp.Name == "YourSprocName"); 

This worked and this caused me to see that the schema is explicitly entered. After some more research, I could not find how you would provide the schema to the stored procedure name.

Later I tried to look under Database which has a property, DefaultSchema. After setting this, this also returned the correct result.

So the simplest solution:

db.DefaultSchema = "schemaName";
StoredProcedure sp = db.StoredProcedures["spName"]; 

Root Cause Analysis

For my specific case, our DBA changed the default schema of the user. 

No comments:

Post a Comment