使用存储过程

时间:2018-05-20 10:04:58

标签: asp.net sql-server stored-procedures sql-server-2014

我正在尝试将asp.net网格数据插入数据库表[DBO].[tbl_family_member]。我为此创建了一个类型typ_fam_mem。但问题是列family_member_id值是从另一个表[DBO].[TBL_FAMILY_HEAD]生成的。请看一下程序。

如何从数据表和过程变量向表中插入数据?

CREATE TABLE [DBO].[tbl_family_member] 
(
    family_member_id bigint identity(1,1) not null,
    family_head_id bigint NOT NULL,
    mem_name nvarchar(200) not null,
    mem_gender tinyint not null,
    mem_occupation nvarchar(50),
    mem_maritial_status tinyint,
    STATUS INT NOT NULL DEFAULT '1',

    CONSTRAINT pk_family_member PRIMARY KEY (family_member_id)
)

create type typ_fam_mem as table
(   
    mem_name nvarchar(200) not null,
    mem_gender tinyint not null,
    mem_occupation nvarchar(50),
    mem_maritial_status tinyint
)

存储过程

CREATE PROCEDURE [dbo].[P_SET_PROFILE_REGISTRATION] 
    (
     --- FOR FAMILY HEAD TABLE
     @P_NAME NVARCHAR(200),
     @P_GENDER TINYINT,
     ---- FOR FAMILY MEMBER
     @P_FAMILY_DT DBO.typ_fam_mem READONLY,
     @V_OUT TINYINT OUTPUT
    )
AS
    DECLARE @FAMILY_HEAD_ID BIGINT;
BEGIN
    SET NOCOUNT ON;

    BEGIN TRY
        INSERT INTO [DBO].[TBL_FAMILY_HEAD] ([NAME], [GENDER])
        VALUES (@P_NAME, @P_GENDER)

        SET @FAMILY_HEAD_ID = SCOPE_IDENTITY();

        IF @@ROWCOUNT > 0
        BEGIN
            --- block for inserting data into [DBO].[tbl_family_member]
        END
    END TRY
    BEGIN CATCH
    END CATCH
END

2 个答案:

答案 0 :(得分:1)

@P_FAMILY_DTtable type,您可以像普通table一样查询表格类型。 您的插入应该看起来像

INSERT INTO [DBO].[tbl_family_member] 
            (family_head_id, 
             mem_name, 
             mem_gender, 
             mem_occupationm, 
             mem_maritial_status) 
SELECT @FAMILY_HEAD_ID, 
       mem_name, 
       mem_gender, 
       mem_occupation, 
       mem_maritial_status 
FROM   @P_FAMILY_DT 

答案 1 :(得分:1)

您可以使用INSERT...SELECT,使用生成的值指定变量。下面的示例还添加了事务管理(适用于多表插入,除非客户端应用程序管理事务)和错误处理。

CREATE PROCEDURE [dbo].[P_SET_PROFILE_REGISTRATION] 
     --- FOR FAMILY HEAD TABLE
     @P_NAME NVARCHAR(200),
     @P_GENDER TINYINT,
     ---- FOR FAMILY MEMBER
     @P_FAMILY_DT DBO.typ_fam_mem READONLY,
     @V_OUT TINYINT OUTPUT
AS
DECLARE @FAMILY_HEAD_ID BIGINT;
SET NOCOUNT ON;
SET XACT_ABORT ON;

BEGIN TRY

    BEGIN TRAN;

    INSERT INTO [DBO].[TBL_FAMILY_HEAD] ([NAME], [GENDER])
    VALUES (@P_NAME, @P_GENDER)

    SET @FAMILY_HEAD_ID = SCOPE_IDENTITY();

    INSERT INTO dbo.tbl_family_member(
              mem_name
            , mem_gender
            , mem_occupation
            , mem_maritial_status
            , family_head_id
        )
    SELECT 
              mem_name
            , mem_gender
            , mem_occupation
            , mem_maritial_status
            , @FAMILY_HEAD_ID
    FROM @P_FAMILY_DT;

    COMMIT;

END TRY
BEGIN CATCH
    IF @@TRANCOUNT > 0 ROLLBACK;
    THROW;
END CATCH;
GO