【发布时间】:2011-11-16 20:36:58
【问题描述】:
我有一个被要求修改的 SQL 命令,但我遇到了一些麻烦,因为我传递给 SQL 的内容现在可以为空。如果我要传递一个值,我可以依赖 SQL 中的 columnName = @parameterName,但是对于 NULL,我无法传递 null 或 DBNull 并使其正确解析。
这是 SQL 伪代码:
SELECT
Columns
FROM
ClientSetup
WHERE
Client_Code = @ClientCode AND
Package_Code = @PackageCode AND
Report_Code = @ReportCode
问题是现在@ReportCode 可以有效地为NULL。在我设置 SqlCommand 的 C# 代码中,我可以输入:
cmd.Parameters.Add("@ReportCode", SqlDBType.VarChar, 5).Value = reportType;
//reportType is a string, which can be null
但是,如果 reportType 为 null,我需要在 SQL 中使用 Report_Code IS NULL,而不是 Report_Code = @reportCode。
我找到的解决方案是将最后一个 where 子句更改为以下内容:
((@ReportCode IS NULL AND Report_Code IS NULL) OR Report_Code = @ReportCode)
和参数短语到
cmd.Parameters.Add("@ReportCode", SqlDBType.VarChar, 5).Value = string.IsNullOrEmpty(reportType) ? System.DBNull : reportType;
这有什么作用,但我想知道是否有人知道在从 .NET 代码向 SQL 传递内容时,是否有更简洁或更好的方法来处理可空参数。
【问题讨论】:
标签: sql-server sqlcommand