我有一个要求,插入数据到表中,其中表名是动态这里是实际的查询: -
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'
这样的变量值动态插入到表中。我可以这样做吗?
实现此目的的一种方法是使用如下的动态查询。
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