【发布时间】:2017-06-30 13:58:14
【问题描述】:
我是 ASP.net 和其中的 UDT 概念的新手。我曾经在 PHP 上工作,所以我很难理解 UDT 的概念。
这是为将输入表单中的数据插入数据库(SQL Server)而编写的存储过程。
代码运行良好,由我公司的高级开发人员编写。
CREATE Procedure [dbo].[Save_Supplier]
@Supplier_UDT Supplier_UDT Readonly,
@UserName varchar(80)
AS
Begin
-------------Block 1------
Declare @TP Table(ID int,Suppliercode varchar(80),Suppliername varchar(80),GSTVATNumber int,Description varchar(80),Productlist varchar(80),Bankdetails varchar(80),
pymenttermdescription varchar(80),Currency int,Pendingpayement Varchar(80),pendingorders int,Active bit )
-------------Block 2------
Insert into @TP(ID ,Suppliercode ,Suppliername,GSTVATNumber,Description ,Productlist,Bankdetails,pymenttermdescription,Currency,Pendingpayement ,pendingorders ,Active)
select ID ,Suppliercode ,Suppliername,GSTVATNumber,Description ,Productlist,Bankdetails,pymenttermdescription,Currency,Pendingpayement ,pendingorders ,Active from @Supplier_UDT
-------------Block 3------
Update Supplier
set
Suppliercode=a.Suppliercode ,
Suppliername=a.Suppliername
,GSTVATNumber=a.GSTVATNumber
,Description =a.Description
,Productlist=a.Productlist
,Bankdetails=a.Bankdetails
,pymenttermdescription=a.pymenttermdescription
,Currency=a.Currency
,Pendingpayement=a.Pendingpayement
,pendingorders=a.pendingorders
,Active=a.Active
from @TP a inner join Supplier
on a.ID=Supplier.ID
-------------Block 4------
Insert into Supplier(Suppliercode ,Suppliername,GSTVATNumber,Description ,Productlist,Bankdetails,pymenttermdescription,Currency,Pendingpayement ,pendingorders ,Active)
select Suppliercode ,Suppliername,GSTVATNumber,Description ,Productlist,Bankdetails,pymenttermdescription,Currency,Pendingpayement ,pendingorders ,Active
from @TP where ID not in (select ID from Supplier) and Suppliercode!=''
据我了解,Block 1 只是声明临时表/变量的结构。 在块 2 中,用户传递了存储在临时表/变量中的输入数据。
我难以理解Block 3和Block 4
我不明白在 INSERT 查询之前 UPDATE 查询在做什么?
Block 3 和 Block 4 的目的是什么?
(代码运行正常,没有错误。)
【问题讨论】:
-
我们无法知道贵公司业务逻辑的原因。这也是 SO 的题外话
-
块 1/2 似乎是多余的,因为
@TP可以替换为@Supplier_UDT。块 3 使用来自@TP的值和匹配的 ID 更新 Supplier 表,如果@TP的 ID 不在 Supplier 中,则最后插入将它们添加为新行。 -
不需要表变量来保存表值参数的内容。您可以像使用表格一样使用参数。
-
可以使用单个
MERGE语句同时执行INSERT和UPDATE。通过消除局部表变量,proc 也可以是一条语句。 -
只需在第 3 块和第 4 块中使用您现有的代码。但不要使用@TP,而是使用您的表参数。
标签: c# asp.net sql-server stored-procedures user-defined-types