将数据插入 Table 其中 Table 名称是动态的?

Insert Data into Table Where Table Name is Dynamic?

我有一个要求,将数据插入 table 其中 Table 名称是动态的 这是实际的查询:-

INSERT INTO GENERATEBARCODE (BARCODEID, AMUID, GROSS_WT, TARE_WT, PRODUCTCODE, BATCHNO, PREVBARCODEID, LOT, UNAME, STAGE, STATUS)
    SELECT DISTINCT BARCODEID, 'DISPENSEHOLD', IT.GROSS_QUANTITY, IT.TARE_QUANTITY, BM.PRODUCT_CODE, IT.BATCH_NO, 'NA', LOT, 'NA', 'START', 'INPROCESS'
    FROM inserted IT INNER JOIN
         DISPENSE_HOLD BM
         ON IT.BATCH_NO = BM.BATCH_NO;

此处 Table 名称动态变化 我有一个变量 01,02,03 etc 应根据 Generatebarcode+'01' 等变量值将数据动态插入 table 中。我该怎么做?

实现此目的的一种方法是使用如下动态查询。

DECLARE @VER VARCHAR(10)
SET @VER='01'
DECLARE @SQL NVARCHAR(MAX)
SET @SQL = N'INSERT INTO GENERATEBARCODE' + @VER + ' (BARCODEID, AMUID, GROSS_WT, TARE_WT, PRODUCTCODE, BATCHNO, PREVBARCODEID, LOT, UNAME, STAGE, STATUS)
    SELECT DISTINCT BARCODEID, ''DISPENSEHOLD'', IT.GROSS_QUANTITY, IT.TARE_QUANTITY, BM.PRODUCT_CODE, IT.BATCH_NO, ''NA'', LOT, ''NA'', ''START'', ''INPROCESS''
    FROM inserted IT INNER JOIN
         DISPENSE_HOLD BM
         ON IT.BATCH_NO = BM.BATCH_NO;'

EXECUTE sp_executesql @SQL