Reputation: 43768
Does anyone know how to write a script in stored proc to run the table based on the variable (or will it possible to do so?)?
for example: I have 3 tables name called customer, supplier, and support
when user input 1, then run table customer, 2 table supplier and 3 table support
declare @input int;
if @input =1
begin
declare @table varchar(50); set @table = 'customer'
end
if @input =2
begin
declare @table varchar(50); set @table = 'supplier '
end
if @input =3
begin
declare @table varchar(50); set @table = 'support'
end
select *
INTO ##test
from @table
Upvotes: 1
Views: 113
Reputation: 176886
yes you can do it by using dynamic sql "EXEC" or by "Sp_Executesql" command.
Example :
USE Northwind
GO
CREATE TABLE #MyTemp
( RowID int IDENTITY,
LastName varchar(20)
)
DECLARE @SQL nvarchar(250)
SET @SQL = 'INSERT INTO #MyTemp SELECT LastName FROM Employees;'
EXECUTE sp_executesql @SQL
Upvotes: 0
Reputation: 85036
Why do you want to do this? It seems like a bad idea at first glance.
Can you post what your stored procedure is doing and any relevant tables? I suspect that you may be able to either:
There are several issues that come up when you use dynamic SQL that you should be aware of. Here is a fairly comprehensive article on the pros and cons.
Upvotes: 0
Reputation: 4585
IF it really is that simple, why not just repeat the Select?
if @input =1
begin
Select * INTO ##test From customer
end
if @input =2
begin
Select * INTO ##test From supplier
end
if @input =3
begin
Select * INTO ##test From support
end
Upvotes: 1