2009-12-14 83 views
1

我正在创建一个存储过程,用于从表中选择一个值并在另一个过程中使用它。如果搜索到的第一个值不存在,我需要它使用默认值。我是新来的存储过程,所以我不确定最佳实践。为存储的proc select语句设置默认值

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

DECLARE @TheValue nvarchar(50) 

SELECT @TheValue = deviceManager.SystemSettings.Value 
FROM deviceManager.SystemSettings 
WHERE (deviceManager.SystemSettings.Setting = 'expire-terminal-requests' 

什么是最好的解决方案?

+0

它适用于哪个SQL服务器?甲骨文? MySQL的?女士? Informix的? DB2? – wallyk 2009-12-14 17:05:43

+0

MS SQL 2008服务器 – Retrocoder 2009-12-14 17:13:56

回答

4
DECLARE @TheValue nvarchar(50) 

SELECT @TheValue = deviceManager.SystemSettings.Value 
FROM deviceManager.SystemSettings 
WHERE (deviceManager.SystemSettings.Setting = 'expire-terminal-requests' 

-- Assuming @TheValue is an output parameter 
SELECT @TheValue = ISNULL(@TheValue, 10) 
+0

您击败了我! – rfonn 2009-12-14 17:07:37

0

@TheValue如果select没有命中任何行,它将为NULL。而NULL是一个很好的值来表示“找不到”。如果为空

一个技巧是,你必须与is null而不是= null以检查它们,例如:

where @TheValue is NULL 
0

​​3210返回列表中的第一个非空值,也是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) 
1

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

DECLARE @TheValue为nvarchar(50)

SET @TheValue = '某些默认值'

SELECT @TheValue = deviceManager .SystemSettings.Value FROM deviceManager.SystemSettings WHERE deviceManager.SystemSettings.Setting ='expire-terminal-requests'

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

希望这会有所帮助。