I have two very similar tables in our database, and I need to write a stored procedure for my Visual Studio 2010 Web Application to read the data from one of these tables given a table number.
Currently, we only have two tables to select from, but I can see this growing to more as this project grows.
This is sort of what I am trying to do, but this code is not correct:
PROCEDURE [dbo].[spGetData]
@tableID int
AS
BEGIN
SET NOCOUNT ON;
declare @col1 nvarchar(50), @table nvarchar(50)
set @col1=case when @tableID=1 then 'SMRequestID' else 'WHRequestID' end
set @table=case when @tableID=1 then 'SMRequest' else 'WHRequest' end
select @col1 as 'Request', WorkOrder, PartNumber, Qty, EmployeeID
from @table
END
Basically, the ColumnName and TableName depend on the @tableID parameter that will be passed in.
How would I go about doing that?
Note: My searches are not turning up anything related, but I am a C# developer and not a database developer. I imagine this has been asked before, it is just I am not using the right keywords.
One option would be to use a conditional based upon the ID and put the code for a specific table in each section for the table.
I prefer this method to get away from the dynamic sql and allow the database server to get a fighting chance to optimize the thing for speed reasons by precompiling.
NOTE: database servers are pretty bad at string manipulation (create dynamic sql) in general.
EDIT1: EXAMPLE
FOR INSTANCE: THIS SQL
gives you the store procedure names or the default constraints depending on what you pass to the parameter.
EDIT2: Based on OP code: