0

I have quite a few tables which contain some common columns (same name and datatype). On these columns I need to perform the same operations and I would like to do that via a stored procedure. However the only way I can make it work at the moment is using dynamic sql, which I'd rather avoid.

Is there any way to use a stored procedure for different tables (where the table name is handed over as parameter) without using dynamic sql?

asked Aug 22, 2014 at 17:19
2
  • 3
    Why do you want to avoid dynamic SQL? Commented Aug 22, 2014 at 17:35
  • @JonSeigel Because I find it much more difficult to maintain than "normal" sql: Intellisense won't work etc. Basically I don't want to use dynamic SQL as long as there is another approach that's still ok. Good question though. Commented Aug 24, 2014 at 16:35

2 Answers 2

7

The other thing you could do is create a view that unions the like tables together, and include a defined column with the table name, then just do a select against that view with the tablename in the where clause.

CREATE VIEW tablesviews AS
SELECT columns, 'TABLE1' as tablename
FROM Table1
UNION ALL
SELECT columns, 'TABLE2' as tablename
FROM Table2
...
SELECT {some columns}
FROM tableviews
WHERE Tablename=@table and [other where clauses]
answered Aug 22, 2014 at 17:50
0
3

one way i could think of is below..

create proc dynamictable 
( 
@name varchar(100) 
) 
as 
begin 
if @name ='tablename1' 
begin 
select columns from tablename1 
end 
if@name='tablename2' 
begin 
select columns from tablename2 
end 
end 
answered Aug 22, 2014 at 17:39
1
  • It is often seen for event distribution, journals, logs, that the name of a table is selected from another control table, allowing rotation. Commented Mar 14, 2019 at 21:43

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.