2012-11-17 64 views
2

如何为表值参数的空值发送到在C#中的存储过程?发送空值到存储过程

+0

的可能重复[如何传递一个空变量从C#存储过程SQL。网络代码](http://stackoverflow.com/questions/1207404/how-to-pass-a-null-variable-to-a-sql-stored-procedure-from-c-net-code) – krock

回答

-1

您可以添加null作为默认放慢参数值,不,如果你希望它是空发送任何价值

例如:

create procedure sp_name(@param1 varhcra(10), @param2 varchar(10)=null) 

C#

command.Parameters.AddWithValue("@param1", "value1"); 
//dont pass any value for param2, it is considered null 
+1

** Do不要**为你自己的存储过程使用'sp_'前缀!该前缀是**由Microsoft **保留供其自己使用。 –

0

使用DBNull.Value通过NULL

3

有使用DBNull.Value虽然小的问题。比方说,我在名为IO的存储过程中有一点点。

的存储过程

CREATE PROCEDURE [dbo].[stp_Check] 
    @IO BIT 

然后,在代码我添加参数如下。

object parameter = new SqlParameter("IO", true); //using false is the same. 

然后我称之为存储过程

_repositary.DataContext.Database.SqlQuery<CallDetail>("exec stp_Check @IO", parameter)(); 

这里_repository是我DataRepository类上下文。知道它会执行sp就足够了。

你能赶上使用SQL Server Profiler呼叫。这将生成如下。

declare @p24 int 
set @p24=7 
exec sp_executesql N'exec stp_Check @IO', --parameter passed 
N'@IO bit', -- parameter with the type passed 
@IO=1 --parameter value used when executing the sp 
select @p24 

问题是这样的。当您使用DBNull.Value创建参数时,如下所示。

object parameter = new SqlParameter("IO", (object)DBNull.Value); 

从SQL Server Profiler可以找出什么是

declare @p24 int 
set @p24=7 
exec sp_executesql N'exec stp_Check @IO', --parameter passed 
N'@IO nvarchar(4000)', -- the passes type is not boolean 
@IO=NULL --parameter value is NULL 
select @p24 

真,这将work.But这不是什么打算。我更喜欢

using System.Data.SqlTypes; 

您可以按如下方式传递null。

object parameter = new SqlParameter("IO", System.Data.SqlTypes.SqlBoolean.Null); 

然后请求是这样的。

declare @p24 int 
set @p24=7 
exec sp_executesql N'exec stp_Check @IO', --parameter passed 
N'@IO bit', -- the passes type is boolean 
@IO=NULL --parameter value is NULL 
select @p24 

有所有的SQLType如int,BIGINT,日期时间等,希望这有助于空值。干杯。 :)