C# 从代码调用的存储过程的行为不同于在SQL Management Studio中使用空值调用的存储过程
这是存储过程C# 从代码调用的存储过程的行为不同于在SQL Management Studio中使用空值调用的存储过程,c#,sql-server,C#,Sql Server,这是存储过程 CREATE PROCEDURE [Proc_DeleteSpecificRow] @p_Id int ,@p_subId int ,@p_col1 varchar(50) = NULL ,@p_col2 varchar(50) = NULL ,@p_col3 varchar(50) = NULL AS BEGIN if(@p_col2 is not null AND @p_col3 is not null) Delete from Tes
CREATE PROCEDURE [Proc_DeleteSpecificRow]
@p_Id int
,@p_subId int
,@p_col1 varchar(50) = NULL
,@p_col2 varchar(50) = NULL
,@p_col3 varchar(50) = NULL
AS
BEGIN
if(@p_col2 is not null AND @p_col3 is not null)
Delete from TestTable where Id= @p_Id AND SubId= @p_subId
AND col2= @p_col2 AND col3= @p_col3
当我在SQL Server management studio中使用以下值运行此存储过程时,它可以完美地工作:
- ID=1
- SubId=4
- col1=empty/null(我认为这就解决了问题!下面将详细介绍)
- col2=A
- col3=X
- ID为DbType.Int16
- 子ID为DbType.Int16
- col1作为DbType.String
- col2作为DbType.String
- col3作为DbType.String
null值的问题可能是如果参数为null,则where子句中的检查,因为例如col2=null将不起作用。
相反,您可以对所有列尝试这样的
和(@p_col2为NULL或@p_col=col2)
。另一种方法是像ISNULL(@p_col,999)=ISNULL(col2,999)
当您从c sharp调用存储过程时,您可以从SQL Server Profiler中看到,语句是真还是假 我认为问题在于您没有向存储过程发送null值param。
您可以使用DBNull.Value
像这样传递null值
MySqlHelper.AddParameter(cmd, "p_col1", DbType.String,
string.IsNullOrEmpty(col1)? DBNull.Value : col1);
MySqlHelper.AddParameter(cmd, "p_col2", DbType.String,
string.IsNullOrEmpty(col2) ? DBNull.Value : col2);
MySqlHelper.AddParameter(cmd, "p_col3", DbType.String,
string.IsNullOrEmpty(col3) ? DBNull.Value : col3);
另一个解决方案是将存储过程更改为
if(isnull(@p_col2,'') != '' AND isnull(@p_col3,'') != '')
begin
-- do stuff
end
我想你也应该添加C代码。好的,我添加了,但问题在本文中描述。我看到你的参数
@p#u Id
在SP中是uniqueidentifier
,但在C代码中它是int
这只是我的第一个版本中的一个输入错误,我将对其进行编辑,正如你所看到的,之前有一个null检查,所以你的情况永远不会发生:如果(@p_col2不为null,@p_col3不为null)。同样,它在SQL Management Studio中也可以工作。
if(isnull(@p_col2,'') != '' AND isnull(@p_col3,'') != '')
begin
-- do stuff
end