Stored Procedure: turn Table name into Table Varia

2019-08-29 02:37发布

问题:

There are quite a few similar Questions, however i didn't quite find what i was looking for. Since using dynamic SQL in a stored procedure can quickly get cumbersome, I want to pass a table name (Varchar) to a stored procedure, turn that Tablename into a Tablevariable and afterwards work with this Tablevariable for the rest of the procedure. I can't figure out the code for this.

I'm working in SSMS on a SQL Server 2008R2. Currently my code looks similar to this. I lag the middle part to create the @Table Table Variable from the @TableName Varchar Variable

CREATE Procedure [dbo].StoredProc(@Tablename Varchar)
AS
Begin
Declare @Table Table (ColA Varchar, ColB Float)
Declare @result float

-- Something like Insert @Table Select * From @Tablename using Dynamic sql or sth. similar

Select @result = Select sum(ColB) From @Table
End

回答1:

You can combine dynamic SQL and Temporary table storage the following way:

CREATE Procedure [dbo].StoredProc(@Tablename Varchar(100))
    AS
    Begin
    create table #TempTbl (ColA Varchar(100), ColB Float);
    Declare @result float

    declare @dynSQL varchar(max);
    select @dynSQL = 'insert into #TempTbl select 
      cast(val1 as varchar(100)) as ColA, 
      cast(val2 as float) as ColB from ' + COALESCE( @Tablename, 'NULL');
    -- Tablename should contain schema name, 'dbo.' for example
    exec( @dynSQL );
    Select @result = sum(ColB) From #TempTbl
    drop table #TempTbl;
    return @Result;
    End


回答2:

you should set the statement yo need in a variable:

 SET @sqlString='INSERT ' + @Table + ' SELECT * FROM ' + @Tablename

using Dynamic sql or sth. similar"

and then execute it:

 EXEC sp_executesql @sqlString 


回答3:

USE AdventureWorks2012;

DECLARE @TableName NVARCHAR(MAX);

DECLARE @Copy TABLE
(
    [ShiftID] [tinyint] NOT NULL,
    [Name] [dbo].[Name] NOT NULL,
    [StartTime] [time](7) NOT NULL,
    [EndTime] [time](7) NOT NULL,
    [ModifiedDate] [datetime] NOT NULL
);

SET @TableName = N'[HumanResources].[Shift]';

INSERT INTO @Copy
EXEC ('SELECT * FROM ' + @TableName);

SELECT * FROM @Copy;