使用存储过程将 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 值插入或更新到数据库表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Query with t(n) and multiple cross joins(使用 t(n) 和多个交叉连接进行查询)
Unpacking a binary string with TSQL(使用 TSQL 解包二进制字符串)
Max rows in SQL table where PK is INT 32 when seed starts at max negative value?(当种子以最大负值开始时,SQL 表中的最大行数其中 PK 为 INT 32?)
Inner Join and Group By in SQL with out an aggregate function.(SQL 中的内部连接和分组依据,没有聚合函数.)
Add a default constraint to an existing field with values(向具有值的现有字段添加默认约束)
SQL remove from running total(SQL 从运行总数中删除)