SQL Server - To write stored procedure - Asked By abinav shankar on 11-Dec-11 10:07 AM

Hi

I want to write a stored procedure which should be as follows

1)I want to select Description from three tables(Producttable,Clienttable,segmenttable) where I will be passing the primary key id and the table name as parameters

how to do it any help will be valued the most
Web Star replied to abinav shankar on 11-Dec-11 10:33 AM
Simply use this stored proc

Create proc spName

(

@id int,

@tableName varchar(50)

)

AS

Begin

  Declare @Sql varchar(MAX)


  Set @Sql = 'Select Description  from ' + @tableName + ' Where id = ' + CAST ( @id as varchar)

  exec(@Sql)

End

You can pass id and tablename to that sp you will get description of the id from passing tablename only you make sure the id and description column should be exists in your all three table.
If the id and description column name different then you need to put two other parameter for that column one for idcolumn and another for selection column so you can create dynamic query in stored proc
 

Sunil Darji replied to abinav shankar on 13-Dec-11 01:02 AM



Create Procedure SP_Name
(
@ID int,
@TableName varchar(50)
)
AS
Begin
  Declare @Query varchar(MAX)
  Set @Query = 'Select Description  from ' + @TableName + ' Where id = ' + convert(varchar,@ID)
  exec(@Query)
End