Tuesday, March 20, 2012

Creating Stored Procedures Based On Variables

Hi There,

I would like to know if for example i have some tables in my DataBase and i need from each table to get for instance, the Name by the ID, how can i make only one procedure which use parameters and variables so i can use this SP to get the Name By ID for all the Tables?

Thanks

You would have to use dynamic SQL in the stored procedure. Assuming all you tables had a unique column named ID and an associated column named NAME, you could create a simple procedure like:
Create Procedure GetNameByID(

@.tableName varchar(100),

@.ID int

)

AS

Begin

Declare @.sql nvarchar(1000)

Set @.sql = N'Select "NAME" From ' + @.tableName + N' Where ID = ' + Convert( varchar(10), @.ID )

exec( @.sql )

End

go

exec GetNameByID 'sysobjects', 1

exec GetNameByID 'syscolumns', 1

And you could get more complicated from there.

No comments:

Post a Comment