【问题标题】:how to set something for null value in a parameter如何在参数中为空值设置一些东西
【发布时间】:2012-05-03 10:27:42
【问题描述】:

我在我的一个应用程序中使用以下程序

ALTER procedure [dbo].[FeeRecordSelect]
@GRNo varchar(4),
@PaymentModeId numeric(2) output
as
begin
SELECT @PaymentModeId = Students.PaymentModeId FROM Students where Students.GRNo = @GRNo
end 
GO

我的问题是:如果我没有得到 @GRNo 的结果,我想在 @PaymentModeId 中选择 1

我已经试过了

create procedure [dbo].[FeeRecordSelect10]
@GRNo varchar(4),
@PaymentModeId numeric(2) output
as
begin
SELECT @PaymentModeId = isnull(Students.PaymentModeId, 1) FROM Students where Students.GRNo = @GRNo
end 
GO

【问题讨论】:

  • 您使用的是哪个 RDBMS?请用适当的重新标记。
  • 可能想查看at this SO article 并考虑在插入null 后检查@paymentModeID 的值,然后将其设置为1。

标签: sql-server-2008 stored-procedures null


【解决方案1】:

IsNull() 不起作用的原因是结果集不包含任何行。

ALTER procedure [dbo].[FeeRecordSelect]  
@GRNo varchar(4),  
@PaymentModeId numeric(2) output
as  
begin  
set @PaymentModeId = isnull((select Students.PaymentModeId FROM Students where Students.GRNo = @GRNo), 1)
end   
GO 

【讨论】:

  • 抱歉,您的代码不起作用。但是 Moos 建议我的工作正常
  • 我猜输出参数不能有默认值...我更新了我的答案以在这种情况下正确使用 IsNull。
【解决方案2】:

@PaymentModeId 仅在选择返回至少一行时才会设置。

Set @PaymentModeId = 1

在选择之前将默认值设置为1。现在如果没有选择行,它仍然会返回1。

编辑:

ALTER procedure [dbo].[FeeRecordSelect]
@GRNo varchar(4),
@PaymentModeId numeric(2) output
as
begin

Set @PaymentModeId = 1    

SELECT @PaymentModeId = Students.PaymentModeId FROM Students where Students.GRNo = @GRNo
end 
GO

【讨论】:

  • 我请求您在我的编码中编辑您的 asnwer.. 这样我就可以准确了解您希望我在哪里使用 set @PaymentModeId = 1
  • 我不知道该怎么做比这更清楚。你没有看到我帖子底部的编辑吗?
  • 感谢 Moose,它正在工作。但我希望有类似 isnull 的东西。
  • 我仍然必须接受你的回答,因为它无论如何都有效
  • 如果可行,将不胜感激并接受答案。如果有一行返回 null,则 isnull 将起作用,但由于没有,因此永远不会进行分配。
猜你喜欢
  • 2017-06-26
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-14
  • 2012-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多