我正在使用 Visual Studio 中的 TableAdapter 查询配置向导编写以下 SQL 查询。
SELECT COUNT(*) AS census
FROM Inventory INNER JOIN Taxonomy ON Inventory.GlobalID = Taxonomy.GlobalID
WHERE (Inventory.Institution = @institution) AND (Inventory.Year = @year) AND
(Inventory.Nending > 0)
我尝试将以下条件添加到 WHERE 子句中:
(Taxonomy.Class = ISNULL(@class, Taxonomy.Class))
这样
1) 仅返回与@class输入参数匹配的行或
2) 所有行都会返回,无论其 TaxonomyGlobal.Class 值如何。
当我将此语句添加到查询中时,调用该查询的 C# 代码会抛出 System.ArgumentNullException 错误,并指出 @class 值不能为 null。
任何有关如何将此条件添加到 WHERE 子句的帮助将不胜感激。
C# 代码:
namespace CollectionMetrics
{
class DatabaseQueries
{
QueryDataSetTableAdapters.InventoryTableAdapter queryAdapter =
new QueryDataSetTableAdapters.InventoryTableAdapter();
public void CensusQuery(string institution, short year, string xclass)
{
int census = 0;
string localClass = xclass;
if (xclass == "All Classes") localClass = null;
census = (int)queryAdapter.CensusBySpecies(localClass, institution, year);
censusOutput.Add(census);
}
}
}
最佳答案
SQL:
(@class IS NULL OR Taxonomy.Class = @class)
由于您使用的是TableAdapter
,因此您需要编辑字段以允许空值:
https://msdn.microsoft.com/en-us/library/ms233762.aspx
设置AllowDbNull 属性
To enable a query to accept null values In the Dataset Designer, select the TableAdapter query that needs to accept null parameter values. Select Parameters in the Properties window and click the ellipsis (…) button to open the Parameters Collection Editor. Select the parameter that allows null values and set the AllowDbNull property to true.
如果您使用SqlParameters
:
C#
var param = new SqlParameter("@class", (object) classVariable ?? DBNull.Value);
将 classVariable
替换为您在代码中使用的变量名称,以设置 @class
SqlParameter
的值。需要强制转换为 object
,因为该变量与 DBNull
的类型不同。
关于c# - 使用 ISNULL 的 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38620681/