如果表中不存在行,我需要知道如何返回默认行.最好的方法是什么?我只从这个特定的表返回一个列来获取它的值.
编辑:这将是SQL Server.
Oracle的一种方法:
SELECT val FROM myTable UNION ALL SELECT 'DEFAULT' FROM dual WHERE NOT EXISTS (SELECT * FROM myTable)
或者在Oracle中:
SELECT NVL(MIN(val), 'DEFAULT') FROM myTable
或者在SqlServer中:
SELECT ISNULL(MIN(val), 'DEFAULT') FROM myTable
这些使用在没有行时MIN()
返回的事实NULL
.
如果您的基本查询只返回一行,那么您可以使用此技巧:
select NVL( MIN(rate), 0 ) AS rate from d_payment_index where fy = 2007 and payment_year = 2008 and program_id = 18
(Oracle代码,不确定NVL是否是SQL Server的正确功能.)
这将消除选择查询从运行两次并且更好的性能:
Declare @rate int select @rate = rate from d_payment_index where fy = 2007 and payment_year = 2008 and program_id = 18 IF @@rowcount = 0 Set @rate = 0 Select @rate 'rate'
这个怎么样:
SELECT DEF.Rate, ACTUAL.Rate, COALESCE(ACTUAL.Rate, DEF.Rate) AS UseThisRate FROM (SELECT 0) DEF (Rate) -- This is your default rate LEFT JOIN ( select rate from d_payment_index --WHERE 1=2 -- Uncomment this line to simulate a missing value --...HERE IF YOUR ACTUAL WHERE CLAUSE. Removed for testing purposes... --where fy = 2007 -- and payment_year = 2008 -- and program_id = 18 ) ACTUAL (Rate) ON 1=1
结果
有效费率存在
Rate Rate UseThisRate ----------- ----------- ----------- 0 1 1
使用的默认费率
Rate Rate UseThisRate ----------- ----------- ----------- 0 NULL 0
测试DDL
CREATE TABLE d_payment_index (rate int NOT NULL) INSERT INTO d_payment_index VALUES (1)