2016-08-23 48 views
1

我有一個包含可爲空的十進制(12,4)列的表。當我這樣查詢時:可空的十進制字段不工作的小巧查詢

const string sqlQuery = "SELECT Id From DummyTable WHERE Price = @Price"; 

var sqlParameter = new { Price = (decimal?)null }; 

此查詢返回0條記錄。但是,當我將查詢更改爲:

const string sqlQuery = "SELECT Id From DummyTable WHERE Price IS NULL; 

此語法起作用。那麼,如何查詢帶參數的可空十進制列?謝謝。

+0

不,你必須使用'IS'與空,你真的可以使用'=' –

+0

'= NULL'在TSQL中不適用於我。它必須是'IS NULL',這可能是您的問題所在...... –

+0

如果我想爲Price = 12.3或類似參數使用相同的函數,該怎麼辦? @CallumLinington – scokmen

回答

1

這不是很性感,但你可以嘗試這樣的事:

[Test] 
public void NullParamTest() 
{ 
    _connection.Execute(@"drop table foo; 
          create table foo(id int not null,price decimal(12, 4) null)"); 
    _connection.Execute("insert into foo values(1, null)"); 
    _connection.Execute("insert into foo values(2, 12.99)"); 

    const string sql = @"select price from foo 
         where coalesce(price, -1) = coalesce(@Price, -1)"; 

    var result = _connection.Query<decimal?>(sql,new { Price = (decimal?)null }).FirstOrDefault(); 
    Assert.That(result, Is.Null); 

    result = _connection.Query<decimal?>(sql,new { Price = 12.99 }).FirstOrDefault(); 
    Assert.That(result, Is.EqualTo(12.99)); 
} 

假設「價格」不能爲負數...