if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[P_{table_source_name}_AddEdit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[P_{table_source_name}_AddEdit]
GO

--标识符不可加引号，且必须遵守所有 Transact-SQL 标识符规则
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

/*
'' ============================================================================================
'' 项目名称：{fyp_title}
'' 项目版本：{fyp_version}
'' 项目描述：{fyp_description}
'' 文件名称：{file_add_name}
'' 文件描述：信息增改存储过程文件{value_match_check value1="{table_description}" value2="" extend_match="unequal"} （{table_description}）{/value_match_check}
'' 公司名称：{fyp_company}
'' 开发人员：{fyp_designer}
'' 创建日期：{fyp_created_date}
'' 修订日期：{system_date_time format="yyyy-MM-dd hh:mm:ss"}
'' 版权信息：{fyp_copyright}

'' 项目升级时需读取以下生成工具的版权信息
'' 生成工具：{fysoft_name}
'' 当前版本：{fysoft_version}
'' 官方网站：{fysoft_website}
'' ============================================================================================
*/

CREATE PROCEDURE dbo.P_{table_source_name}_AddEdit

    --记录未改变时的主键值，用于在修改记录时，传入检索参数值
{fields_loop type="3"}
    @{field_source_name}_PKValueIn {field_datatype_name}{value_match_check value1="{field_datatype_name}" value2="nvarchar|varchar|nchar|char" extend_match="in2"}({field_maxlength}){/value_match_check},{/fields_loop}

    --需保存字段信息的值
{fields_loop separator=","}
    @{field_source_name} {field_datatype_name}{value_match_check value1="{field_datatype_name}" value2="nvarchar|varchar|nchar|char" extend_match="in2"}({field_maxlength}){/value_match_check}{/fields_loop}

AS
BEGIN TRANSACTION
BEGIN
    --是否编辑记录
    DECLARE @bEdit bit
    SET @bEdit = 0

    IF ({fields_loop type="3" separator=" And "}@{field_source_name}_PKValueIn IS NOT NULL{/fields_loop})
    BEGIN
        IF EXISTS (select top 1 * from [{table_name}] where {fields_loop type="3" separator=" And "}[{field_name}] = @{field_source_name}_PKValueIn{/fields_loop})
            SET @bEdit = 1
    END

    IF (@bEdit = 1)
    BEGIN
        UPDATE [{table_name}] SET {fields_loop separator=","}
        {field_bracket_name} = @{field_source_name}{/fields_loop}
        WHERE ({fields_loop type="3" separator=" And "}[{field_name}] = @{field_source_name}_PKValueIn{/fields_loop})
    END
    ELSE
    BEGIN
        INSERT INTO [{table_name}]
        ({fields_loop separator=", "}[{field_name}]{/fields_loop})
        VALUES
        ({fields_loop prefix="@" separator=", "}{field_source_name}{/fields_loop})
    END
END
COMMIT TRANSACTION
IF @@TRANCOUNT > 0 ROLLBACK TRAN
RETURN
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
