使用存储过程更新多个记录

时间:2016-08-19 14:30:11

标签: sql sql-server stored-procedures

作为一名新手,我有一个问题可以帮助我解决我正在处理的问题。

使用下面创建的表,有没有办法修改存储过程以更新表中的多行

CREATE TABLE AccountTable
(
  RowID int IDENTITY(1, 1),
  AccountID varchar(2),
  AccountName varchar(50),
  SeqNum int,
  SeqDate datetime
)

CREATE PROCEDURE [ACCOUNTTABLE_UPDATE]
(
  @SeqNum int,
  @SeqDate datetime,
  @Account_ID varchar(2)
)

AS 
SET NOCOUNT ON
BEGIN
UPDATE AccountTable
SET SeqNum = @SeqNum, SeqDate = @SeqDate
WHERE AccountID = @AccountID
END

EXEC ACCOUNTTABLE_UPDATE  SeqNumValue, SeqDateValue, AccountIDValue

手动运行存储过程当然会编辑一行,添加更多值会导致参数错误太多。我只是想看看这个存储过程是否实际上可以更新表中的多行,或者是否应该修改它实际上处理提供超过3个参数。

1 个答案:

答案 0 :(得分:4)

您可以使用表格值参数(here是一些信息)

首先创建表格类型和SP:

USE MyDB;  
GO  

-- Create a table type.  
CREATE TYPE SomeTableType AS TABLE ( 
    SeqNum int,
    SeqDate datetime,
    Account_ID varchar(2)
);  
GO  

-- Create a procedure to receive data for the table-valued parameter. 
CREATE PROCEDURE [ACCOUNTTABLE_UPDATE]  
    @T SomeTableType READONLY  
AS   
SET NOCOUNT ON  

UPDATE AT
SET SeqNum = t.SeqNum, SeqDate = t.SeqDate
FROM AccountTable AT
INNER JOIN @T t
    ON t.AccountID = AT.AccountID
GO  

然后使用您之前创建的表类型声明表,添加数据并运行SP:

-- Declare a variable that references the type. 
DECLARE @Temp AS SomeTableType;  

-- Add data to the table variable  
INSERT INTO @Temp VALUES
... 

-- Pass the table variable data to a stored procedure.
EXEC [ACCOUNTTABLE_UPDATE]  @Temp;  
GO  

另一种方法是将参数传递为XML:

USE MyDB;  
GO  

CREATE PROCEDURE [ACCOUNTTABLE_UPDATE]  
    @x xml  
AS   
SET NOCOUNT ON  

UPDATE AT
SET SeqNum = t.v.value('@SeqNum','int'), 
    SeqDate = t.v.value('@SeqDate','datetime')
FROM AccountTable AT
INNER JOIN @x.nodes('/row') as t(v)
    ON t.AccountID = t.v.value('@AccountID','varchar(2)')

然后执行它:

DECLARE @x xml = N'<row SeqNum="1" SeqDate="2016-08-01 12:43:08.000" AccountID="AA"/>'

EXEC [ACCOUNTTABLE_UPDATE]  @x;