Insert Data into Table Where Table Name is Dynamic?

时间:2018-03-06 13:02:09

标签: sql-server sql-server-2008 sql-server-2008-r2

I had a Requirement that,Insert into data into table where as Table Name is Dynamic Here Is the actual Query:-

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;

Here Table Name Vary Dynamically I had a Variable Which Gives 01,02,03 etc Data should be inserted dynamically into table based on variable value like Generatebarcode+'01' .How Could I do that?

1 个答案:

答案 0 :(得分: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