1

我有这个 SQL 代码,我用它来一次动态地插入 3 个表。当我尝试运行它时,我收到此消息

消息 137,级别 16,状态 1,过程 InsertData,第 28 行 必须声明标量变量“@RECEIVABLESDATA”。

有任何想法吗?

USE [PantaRei]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[InsertData] 
@RECEIVABLESDATA RECEIVABLESTABLE READONLY,
@DILUTIONSDATA DILUTIONSTABLE READONLY,
@ACCOUNTABLESDATA ACCOUNTABLESTABLE READONLY,
@TABLE1 VARCHAR(MAX),
@TABLE2 VARCHAR(MAX),
@TABLE3 VARCHAR(MAX)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    DECLARE @CMD nvarchar(345)

    SET NOCOUNT ON;

    SET @TABLE1 = RTRIM(@TABLE1)
    SET @TABLE2 = RTRIM(@TABLE2)
    SET @TABLE3 = RTRIM(@TABLE3)

    SET @CMD =

        'INSERT INTO ' + QUOTENAME(@TABLE1) +
        'SELECT * FROM [DBO].' + QUOTENAME(@RECEIVABLESDATA)

    EXECUTE sp_executesql @CMD

    SET @CMD =

        'INSERT INTO ' + QUOTENAME(@TABLE2) +
        'SELECT * FROM [DBO].' + QUOTENAME(@DILUTIONSDATA)

    EXECUTE sp_executesql @CMD

    SET @CMD =

        'INSERT INTO '+ QUOTENAME(@TABLE3) + 
        'SELECT * FROM [DBO].' + QUOTENAME(@ACCOUNTABLESDATA)
END
4

1 回答 1

1

尝试使用临时表:

  SELECT * INTO #t1 FROM @RECEIVABLESDATA;

  SET @CMD =

        'INSERT INTO ' + QUOTENAME(@TABLE1) +
        'SELECT * FROM #t1';

    EXECUTE sp_executesql @CMD

这里也是另一种方式。检查它是否适用于您的 MS SQL 版本:

SET @CMD =

        'INSERT INTO ' + QUOTENAME(@TABLE1) +
        'SELECT * FROM @RECEIVABLESDATA';

    EXECUTE sp_executesql @CMD, N'@RECEIVABLESDATA RECEIVABLESDATA READONLY', @RECEIVABLESDATA;
于 2012-08-15T08:33:37.787 回答