Sql 为存储的proc select语句设置默认值

Sql 为存储的proc select语句设置默认值,sql,sql-server,stored-procedures,Sql,Sql Server,Stored Procedures,我正在创建一个存储过程,它从表中选择一个值并在另一个过程中使用它。如果搜索的第一个值不存在,我需要它使用默认值。我不熟悉存储过程,所以我不确定最佳实践 下面是第一个select语句,它可能返回值,也可能不返回值。如果它不返回值,我需要将“@theValue”设置为10,以便在下一个select语句中使用它 DECLARE @TheValue nvarchar(50) SELECT @TheValue = deviceManager.SystemSettings.Value FROM devi

我正在创建一个存储过程,它从表中选择一个值并在另一个过程中使用它。如果搜索的第一个值不存在,我需要它使用默认值。我不熟悉存储过程,所以我不确定最佳实践

下面是第一个select语句,它可能返回值,也可能不返回值。如果它不返回值,我需要将“@theValue”设置为10,以便在下一个select语句中使用它

DECLARE @TheValue nvarchar(50)

SELECT @TheValue = deviceManager.SystemSettings.Value 
FROM deviceManager.SystemSettings 
WHERE (deviceManager.SystemSettings.Setting = 'expire-terminal-requests'
最好的解决方案是什么?

@如果选择未命中任何行,则该值将为空。NULL是一个很好的值,表示找不到

使用null的一个技巧是必须使用is null而不是=null来检查它们,例如:

where @TheValue is NULL
@如果select未命中任何行,则该值将为NULL。NULL是一个很好的值,表示找不到

使用null的一个技巧是必须使用is null而不是=null来检查它们,例如:

where @TheValue is NULL
coalesce返回列表中的第一个非空值,也是ANSI标准

SET @TheValue = coalesce (some_expresson_that_may_return_null
                         ,some_other_expresson_that_may_return_null
                         ,and_another_expresson_that_may_return_null
                         ,default_value)
coalesce返回列表中的第一个非空值,也是ANSI标准

SET @TheValue = coalesce (some_expresson_that_may_return_null
                         ,some_other_expresson_that_may_return_null
                         ,and_another_expresson_that_may_return_null
                         ,default_value)

另一种可能性是,在查询之前设置默认值

声明@TheValue nvarchar50

设置@TheValue='一些默认值'

选择@TheValue=deviceManager.SystemSettings.Value 从deviceManager.SystemSettings 其中deviceManager.SystemSettings.Setting='expire terminal requests'

这将始终返回默认值或正确值


希望这有帮助。

另一种可能性是,在查询之前设置默认值

声明@TheValue nvarchar50

设置@TheValue='一些默认值'

选择@TheValue=deviceManager.SystemSettings.Value 从deviceManager.SystemSettings 其中deviceManager.SystemSettings.Setting='expire terminal requests'

这将始终返回默认值或正确值


希望这能有所帮助。

它适用于哪台SQL server?神谕MySQL?太太Informix?DB2?它用于哪个SQL服务器?神谕MySQL?太太Informix?DB2?