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

时间:2014-06-04 11:24:51

标签: sql sql-server tsql stored-procedures

有很多类似的问题,但我找不到我想要的东西。 由于在存储过程中使用动态SQL很快就会变得很麻烦,我想将表名(Varchar)传递给存储过程,将Tablename转换为Table变量,然后在此过程的其余部分使用此Table变量。 我无法弄清楚这个代码。

我在SQL Server 2008R2上使用SSMS。目前我的代码看起来与此类似。我迟到中间部分从@TableName Varchar变量

创建@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

3 个答案:

答案 0 :(得分:0)

你应该在变量中设置你需要的语句:

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

使用Dynamic sql或sth。类似"

然后执行它:

 EXEC sp_executesql @sqlString 

答案 1 :(得分:0)

您可以通过以下方式组合动态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

答案 2 :(得分:0)

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;