Tuesday, March 20, 2012

[SS2K5] : Dynamically construct a FROM statement with current SCHEMA

Hi,

I've got a DB with some schemas.

There's same tables under these schemas as for example :

MySchema1.MyTable1

MySchema2.MyTable1

I wrote CRUD stored procedures for these tables.

I'd like to dynamically create the FROM statement inside the stored procedures by getting the schema name from the current context.

Kind of :

FROM SCHEMA_NAME().MyTable1

So I'll have one generic stored procedure for MyTable1.

This stored proc will be under the DB level and will not have to be replicate under all the schemas.

Is it possible ?

Thanks for any help.

BERTRANDR

Sure, sp_executesql is such a utility to run dynamic sql. Basically you construct a SQL string(NVARCHAR) with parameters first, then use sp_executesql to execute it. Look at Book Online for details.|||Why do you want to use a generic SP? Using dynamic SQL has lot of issues - complexity, performance (it depends on the case), security risks, permissions management, debugging pain, ownership chaining issues in your case etc. You should create a SP in each schema that handles the modifications for each table. This is much more robust, simpler to manage, debug, code etc.|||

Well my point is that I don t want to duplicate objects that have the same purposes and do exactly the same things for the same table but under differents schemas.

I thought it was the best thing to do .

But maybe am I wrong ..

No comments:

Post a Comment