PL SQL“数组类型”到TSQL的翻译

时间:2019-05-06 14:31:21

标签: sql-server tsql plsql

这是我最初的PL / SQL代码:

    TYPE VarcharArray IS TABLE OF VARCHAR2(100) INDEX BY BINARY_INTEGER;

并且我在以下代码中使用它:

 PROCEDURE Create(inFatherId IN VARCHAR2, inBarcode IN VarcharArray, inItemId IN VarcharArray)
 IS
    myCount NUMBER(38);
    sampleId_FromDb NUMBER(38);
    itemId_FromDb NUMBER(38);
 BEGIN
    myCount := inBarcode.COUNT;
    FOR i IN 1..myCount
    LOOP
        SELECT ITEM.Id INTO itemId_FromDb FROM ITEM WHERE FatherId = inFatherId AND CampaignItemId = inItemId(i);
        SELECT SAMPLE_SEQUENCE.NEXTVAL INTO sampleId_FromDb FROM DUAL;
        INSERT INTO CAMPAIGN_SAMPLES(Id, Barcode, ItemId) VALUES(sampleId_FromDb, inBarcode(i), itemId_FromDb);
    END LOOP;
 END;

我已经看到可以使用表值参数将数组类型转换为MS SQL,但是如何以类似的方式进行迭代,以便在迭代中包含thee操作?

在当前的PL / SQL实现中,我在数组中最多发送50.000个元素,并且性能不错。我也希望在MS SQL中也有类似的事情。

1 个答案:

答案 0 :(得分:1)

不需要循环并一次插入一行。那只是使代码变慢的一种方法。由于表中没有任何顺序,因此您需要添加一列以定义顺序。您的类型如下:

CREATE TYPE VarcharArray AS TABLE(ID int, Item VARCHAR(100));

然后,您可以将过程重写为单个INSERT语句。

CREATE PROCEDURE SomeProcedure(
    @FatherId AS VARCHAR, --This might need a length or will be defaulted to length 1
    @Barcode  AS VarcharArray READONLY, 
    @ItemId   AS VarcharArray READONLY
)
AS
    INSERT INTO CAMPAIGN_SAMPLES(Id, Barcode, ItemId) 
    SELECT NEXT VALUE FOR SAMPLE_SEQUENCE,
        bc.Item,
        i.Id 
    FROM ITEM i
    JOIN @ItemId ii ON i.CampaignItemId = ii.Item
    JOIN @Barcode bc ON ii.ID = bc.ID
    WHERE i.FatherId = @FatherId;

您还可以使用两个值创建一个表,并防止可能发生的任何排序问题。

CREATE TYPE BarcodeItems AS TABLE(Item VARCHAR(100), Barcode VARCHAR(100));

GO
CREATE PROCEDURE SomeProcedure(
    @FatherId AS VARCHAR, --This might need a length or will be defaulted to length 1
    @BarcodeItems  AS BarcodeItems READONLY
)
AS
    INSERT INTO CAMPAIGN_SAMPLES(Id, Barcode, ItemId) 
    SELECT NEXT VALUE FOR SAMPLE_SEQUENCE,
        bi.Item,
        i.Id 
    FROM ITEM i
    JOIN @BarcodeItems bi ON i.CampaignItemId = bi.Item
    WHERE i.FatherId = @FatherId;