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 @tabl开发者_如何学运维e = '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
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
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
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:
- Modify your schema in such a way that you would no longer to do this
- Create different stored procedures to do what you want on each table instead of forcing it into one proc.
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.
精彩评论