在表名为动态的情况下将数据插入表中?

问题描述 投票:2回答:1

我有一个要求,插入数据到表中,其中表名是动态这里是实际的查询: -

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;

这里表名称动态变化我有一个变量,它给01,02,03 etc数据应该基于像Generatebarcode+'01'这样的变量值动态插入到表中。我可以这样做吗?

sql-server sql-server-2008 sql-server-2008-r2
1个回答
2
投票

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

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
© www.soinside.com 2019 - 2024. All rights reserved.