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

时间:2014-08-13 09:23:04

标签: sql-server tsql stored-procedures

我有一张表Cars,如下所示:

CarsTable

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

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

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

请告诉我如何在存储过程中实现此目的。

我的尝试:

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,如下所示

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

MERGE Cars AS T
USING (SELECT id, Model, Company from @dtTypeCars) AS S
ON T.id = S.id
WHEN MATCHED THEN
    UPDATE SET T.Model = S.Model,T.Company = S.Company
WHEN NOT MATCHED BY TARGET THEN
    INSERT (id,Model,Company) VALUES (S.id, S.Model, S.Company)
WHEN NOT MATCHED BY SOURCE THEN
    DELETE;