> For the complete documentation index, see [llms.txt](https://help.besmart.software/erpc/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://help.besmart.software/erpc/data-interface-reference-manual/data-interface/data-tables-relations/stored-procedure-ecwriteentity.md).

# Stored procedure EcWriteEntity

helper procedure to write data into DI – mainly for bulks consisting of more than one EcENTITY row

<table data-header-hidden><thead><tr><th width="200"></th><th></th><th></th><th></th></tr></thead><tbody><tr><td><strong>parameter</strong></td><td><strong>type</strong></td><td><strong>direction</strong></td><td><strong>description</strong></td></tr><tr><td><strong>@EntName</strong></td><td>nvarchar (100) Required</td><td>Input</td><td>Entity name – for description, see Table EcENTITY, field ‘name’</td></tr><tr><td><strong>@BulkId</strong></td><td>int Optional</td><td>InputOutput</td><td><p>Transfer request bulk_id – see remarks under Table EcENTITY description</p><ul><li>use NULL value to create a first EcENTITY row;</li></ul><p>the procedure creates a new bulk_id value and passes it back</p><ul><li>for writing next EcENTITY rows (within one bulk) use the value which this procedure returned in this parameter when writing the first EcENTITY row</li></ul></td></tr><tr><td><strong>@EnClassID</strong></td><td><p>nvarchar(10)</p><p>Optional</p></td><td>Input</td><td><p>Entity type</p><p>if omitted, ‘ITEM’ value is used</p></td></tr><tr><td><strong>RetValue</strong></td><td>bigint</td><td>ReturnValue</td><td>EcENTITY.id inserted</td></tr></tbody></table>

The source code:

```sql
CREATE PROCEDURE [dbo].[EcWriteEntity]
    @EntName NVARCHAR (100),
    @BulkID INT = -1 OUT,
    @EntClassID NVARCHAR (10) = 'ITEM'
AS
BEGIN
    -- check mandatory fields:
    IF @EntClassID IS NULL
    BEGIN
        RAISERROR('@EntClassID parameter is NULL', 16, 1);
        RETURN -1;
    END
    IF @EntName IS NULL
    BEGIN
        RAISERROR('@EntName parameter is NULL', 16, 1);
        RETURN -1;
    END
    -- SET NOCOUNT ON added to prevent extra result sets from interfering with SELECT statements:
    SET NOCOUNT ON;
    DECLARE @InsertedID BIGINT;
    DECLARE @result TABLE ( bid int, rid bigint );
    IF @BulkID IS NULL OR @BulkID < 0
    BEGIN
        INSERT INTO EcENTITY
        (ent_class_id, name, comm_dir, bulk_id)
        OUTPUT INSERTED.bulk_id, INSERTED.id INTO @result
        VALUES
        ( @EntClassID, @EntName, 1, ISNULL((SELECT MAX(bulk_id) FROM EcENTITY), 0) + 1);
    END
    ELSE
    BEGIN
        INSERT INTO EcENTITY
        (ent_class_id, name, comm_dir, bulk_id)
        OUTPUT INSERTED.bulk_id, INSERTED.ID INTO @result
        VALUES
        ( @EntClassID, @EntName, 1, @BulkID);
    END
    
    SET @BulkID = (SELECT TOP 1 bid FROM @result);
    SET @InsertedID = (SELECT TOP 1 rid FROM @result);
    RETURN @InsertedID;
END

```
