sql-server-2005 – 在SQL Server 2005中向存储过程添加参数之间的区别

我想知道这两个符号之间的区别.

首先,我有一个存储过程

CREATE PROCEDURE AddSomething( @zonename varchar(50),@desc varchar(255),@TheNewId int OUTPUT ) AS 
BEGIN 
   INSERT INTO a_zone(zonename,descr) VALUES(@zonename,@desc) 
   SELECT @TheNewId = ScopE_IDENTITY()         
END

如果我以这种方式添加参数有什么区别

sqlCommand Cmd = new sqlCommand("AddSomething",oConn); 
Cmd.CommandType = CommandType.StoredProcedure; 
sqlParameter oParam1 = Cmd.Parameters.AddWithValue("@zonename",sName);
sqlParameter oParam2 = Cmd.Parameters.AddWithValue("@desc",description);

sqlCommand Cmd2 = new sqlCommand("AddSomething",oConn); 
Cmd2.CommandType = CommandType.StoredProcedure;
cmd2.Parameters.Add("@zonename",sqlDbType.VarChar).Value = zonename.Text.Trim();
cmd2.Parameters.Add("@desc",sqlDbType.VarChar).Value = desc.Text.Trim();

请帮帮我

谢谢你的期待

解决方法

以下是一些解释:

difference between command Add and AddWithValue

Dim cmd as new sqlCommand("SELECT * FROM MyTable WHERE MyDate>@TheDate",conn)
cmd.Parameters.Add("@TheDate",sqlDbType.DateTime).Value="2/1/2007"

VS

cmd.Parameters.AddWithValue("@TheDate","2/1/2007")

“当进入参数时,Add强制从字符串到日期的转换.AddWithValue只是将字符串传递给sql Server.

When using Parameters.Add – the S qlDbTypeis kNown at compile time

When using Parameters.AddWithValue the method has to Box and unBox the value to find out it’s type.

Additional benefits of the former is that Add is a bit more code safe
and will assist against sql injection attacks,code safe in terms
that if you try to pass a value that doesn’t match the sqldb type
defined – the error will be caught in .Net code and you will not have
to wait for the round trip back.

> http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx
> http://msdn.microsoft.com/en-us/library/yy6y35y8.aspx

编辑:

获取输出参数的示例:

C#

cmd.Parameters.Add(new sqlParameter("@TheNewId",sqlDbType.Int,int.MaxValue));
cmd.Parameters("@TheNewId").Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
int theNewID = (int)cmd.Parameters("@TheNewId").Value;

VB.Net

cmd.Parameters.Add(New sqlParameter("@TheNewId",Int32.MaxValue))
cmd.Parameters("@TheNewId").Direction = ParameterDirection.Output
cmd.ExecuteNonQuery()
Dim theNewID As Int32 = DirectCast(cmd.Parameters("@TheNewId").Value,Int32)

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 'EastRiver' 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...