使用存储过程将 DataTable 值插入或更新到数据库表

INSERT or Update DataTable values into a database table using stored procedure(使用存储过程将 DataTable 值插入或更新到数据库表中)
本文介绍了使用存储过程将 DataTable 值插入或更新到数据库表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表 Cars 如下:

此表将在 C# 应用程序的网格中读取.应用程序可以编辑或删除或添加新行.更新后的网格将被作为参数传递给存储过程.

This table will be read in grid of a C# application. The application can either edit OR delete OR add a new row. The updated grid will be take in a datatable as be passed as a parameter to the Stored Procedure.

我想开发一个以 @typeCars 作为输入的存储过程.

I want to develop a stored procedure which takes @typeCars as input.

现在应该更新 Cars 表中已编辑的列,应该删除已删除的列并添加新列.

Now the edited columns should be updated in the Cars table, deleted columns should be deleted and new columns should be added.

请告诉我如何在存储过程中实现这一点.

Please let me know how to achieve this in a stored procedure.

我的尝试:

CREATE PROC sp_updateDataTable (@dtTypeCars dtTypeCars READONLY)
AS 
BEGIN
   BEGIN TRY
      DECLARE @dbMaxCarIdval INT;
      DECLARE @typeCurrentCarIdVal INT;

      SELECT TOP 1 @dbMaxCarIdval = id FROM Cars ORDER BY id DESC

      IF (@dbMaxCarIdval >= (SELECT id FROM @dtTypeCars))
      BEGIN
          UPDATE Cars 
          SET Model = (SELECT Model FROM @dtTypeCars), 
              Company = (SELECT Company FROM @dtTypeCars)
          WHERE id = (SELECT id FROM @dtTypeCars);
      END
 END TRY
 BEGIN CATCH
     PRINT 'I am in Catch';
 END CATCH
END

请注意 dtTypeCars 是一个 TYPE 如下

Please note dtTypeCars is a TYPE as follows

CREATE TYPE dtTypeCars AS TABLE
(
 id INT NOT NULL,
 Model varchar(50),
 Company varchar(50)
)

推荐答案

使用Merge语句更新、插入和删除数据http://technet.microsoft.com/en-在/library/bb522522(v=sql.105).aspx

Use Merge statement to update,insert and delete the data http://technet.microsoft.com/en-in/library/bb522522(v=sql.105).aspx

这篇关于使用存储过程将 DataTable 值插入或更新到数据库表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
How can I generate an entity–relationship (ER) diagram of a database using Microsoft SQL Server Management Studio?(如何使用Microsoft SQL Server Management Studio生成数据库的实体关系(ER)图?)