简体   繁体   English

存储过程:将表名称转换为表变量

[英]Stored Procedure: turn Table name into Table Variable

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. 由于在存储过程中使用动态SQL会很快变得麻烦,因此我想将表名(Varchar)传递给存储过程,将该表名转换为Tablevariable,然后在其余过程中使用此Tablevariable。 I can't figure out the code for this. 我不知道这个代码。

I'm working in SSMS on a SQL Server 2008R2. 我正在SQL Server 2008R2的SSMS中工作。 Currently my code looks similar to this. 目前,我的代码与此类似。 I lag the middle part to create the @Table Table Variable from the @TableName Varchar Variable 我落后于中间部分,从@TableName Varchar变量创建@Table Table变量

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

you should set the statement yo need in a variable: 您应该在变量中设置您需要的语句:

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

using Dynamic sql or sth. 使用动态SQL或其他。 similar" 类似”

and then execute it: 然后执行它:

 EXEC sp_executesql @sqlString 

You can combine dynamic SQL and Temporary table storage the following way: 您可以通过以下方式组合动态SQL和临时表存储:

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
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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM