从数据层向存储过程多次插入值的最佳方法?
你好 我有 DAL 层,从那里调用存储过程将值插入表中。
例如:-
CREATE PROCEDURE [dbo].[DataInsert]
@DataName nvarchar(64)
AS
BEGIN
INSERT INTO
table01 (dataname)
VALUES
(@dataname)
END
现在随着需求的变化,每个客户请求我必须添加值 5 次。那么最佳实践是什么?
我是否从 DAL 调用此存储过程 5 次?
或者
一次性将所有值(可能以逗号分隔)传递给存储过程,然后让存储过程添加 5 次?
顺便提一句。并不总是5次。它是可变的。
Hi
I have DAL Layer, from where invoking a stored procedure to insert values into the table.
E.g.:-
CREATE PROCEDURE [dbo].[DataInsert]
@DataName nvarchar(64)
AS
BEGIN
INSERT INTO
table01 (dataname)
VALUES
(@dataname)
END
Now as requirement changed, per client request i have to add values 5 times. So what is the best practice?
Do i call this Stored Procedure 5 times from my DAL?
or
Pass all the values (may be comma separated) to storedprocedure in one go and then let the stored procedure add it for 5 times?
BTW. Its not always 5 times. It is changeable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以创建用户定义的表类型;
如此定义您的存储过程;
然后,您需要创建一个与架构匹配的数据表(下面称为表)并按如下方式调用存储过程;
You could create a user-defined table type;
Define your stored proc as such;
Then you'll need to create a datatable (called table below) that matches the schema and call the stored proc as so;
顺便说一句,这个过程有效 - 我刚刚编写并测试了它,请参阅下面的结果!
然后运行它:-
EXEC @return_value = [dbo].[DataInsert]
@DataName = N' Five, Bits, of, your, data'
来自 table01 的行:*
5
位
的
数据
*
(受影响的 5 行)
btw this proc works - I've just written and tested it see results below!
then run it: -
EXEC @return_value = [dbo].[DataInsert]
@DataName = N'five, bits, of, your, data'
*rows from table01: *
five
bits
of
your
data
(5 row(s) affected)
我要么重复调用您的过程(这将是我的选择),要么您可以使用 XML 将值列表作为单个参数传递。
http://support.microsoft.com/kb/555266
I'd either call your proc repeatedly(that would be my choice), or else you could use XML to pass in a list of values as a single parameter.
http://support.microsoft.com/kb/555266
我不想使用难以维护且不可扩展的花哨 SQL 代码,而是直接多次调用存储过程。
如果性能或事务行为存在问题,您可以考虑单批发送命令。
你谈到了 5 个插入。如果要插入的记录数量较多,您也可以考虑批量插入。
Instead of fancy SQL code that is difficult to maintain and is not scalable, I would simply go to invoking your stored procedure multiple times.
If performance or transactional behavior is an issue, you can consider to send the commands in a single batch.
You talked about 5 insert. If the number of record to insert is much greater, you could consider bulk insert as well.