未找到结果时在 t-sql 中选择默认值的有效方法

发布于 2024-10-04 03:44:18 字数 865 浏览 6 评论 0原文

好吧,这是一个非常简单的问题,但我很好奇:就效率和风格而言,最好的方法是什么?

我经常需要在 MS SQL 中选择数据,但我正在寻找单个结果。如果数据库中没有匹配项,我想返回默认值。

以下是我采取的一些方法:

在代码中执行

--Regular Select in SQL
SELECT myValue FROM dbo.SomeTable WHERE id = @id


//In Data Access Layer
using (IDataReader reader = cmd.ExecuteReader()) {
    if (reader.Read()) {
        return Convert.ToInt32(reader["myValue"]);
    }else {
        return 0; //return a default
    }
}

保证 SQL 中的返回值

--SQL stores in a variable and selects null value if available
declare @myVal int
select @myVal = myValue FROM dbo.SomeTable WHERE id = @id

--return value or a default
select ISNULL(@myVal,0) as myValue


//In Data Access Layer
return Convert.ToInt32(cmd.ExecuteScalar());

有没有更优雅的方法来做到这一点?或者更有效的方法?

如果不是,您认为哪种做法更好?

OK, this is a pretty simple problem, but I'm curious: what is the best approach in terms of efficiency and style?

I often need to select data in MS SQL, but am looking for a single result. If there is no match in the database, I'd like to return a default value.

Here are a few approaches I take:

Do it in Code

--Regular Select in SQL
SELECT myValue FROM dbo.SomeTable WHERE id = @id


//In Data Access Layer
using (IDataReader reader = cmd.ExecuteReader()) {
    if (reader.Read()) {
        return Convert.ToInt32(reader["myValue"]);
    }else {
        return 0; //return a default
    }
}

Guarantee a returned value in SQL

--SQL stores in a variable and selects null value if available
declare @myVal int
select @myVal = myValue FROM dbo.SomeTable WHERE id = @id

--return value or a default
select ISNULL(@myVal,0) as myValue


//In Data Access Layer
return Convert.ToInt32(cmd.ExecuteScalar());

Is there a more elegant way to do this? Or a more efficiient way?

If not, which of these would you consider a better practice?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

赴月观长安 2024-10-11 03:44:18

我会使用 ISNULL(field, replacement_value_if_null) ,它是一个本机 T-SQL 函数,并且全部由 SQL Server 端完成,因此更易于调试。

如果有人在性能方面提供一些意见,那可能会有用!

I would use ISNULL(field, replacement_value_if_null) its a native T-SQL function and its all done from the SQL Server side so more easy to debug.

If someone has some input in terms of performance, that might be usefull!

梦在夏天 2024-10-11 03:44:18
((int?)cmd.ExecuteScalar()).GetValueOrDefault();

或者

((int?)cmd.ExecuteScalar())??0;

我猜是你想要的

((int?)cmd.ExecuteScalar()).GetValueOrDefault();

or

((int?)cmd.ExecuteScalar())??0;

Is what you want I guess

还不是爱你 2024-10-11 03:44:18

在我看来,返回 NULL 或返回零之间没有太大区别。无论哪种方式,您的代码仍然必须执行与返回结果时不同的操作。你仍然会有一个if-else。如果返回一条记录,则执行此操作,否则执行其他操作。所以我真的看不出有多大区别。

我鼓励您不要使用 DataReader 返回单个值。最好使用ExecuteScalar,或者为了获得更好的性能,使用存储过程的输出参数。

It doesn't seem to me that there is much difference between returning a NULL or returning a zero. Either way, your code still has to do something different than it would do if a result was returned. You're still going to have an if-else. If a record is returned, do this, else do some other thing. So I don't really see much difference.

I would encourage you not to use a DataReader to return a single value. It would be better to use ExecuteScalar, or for better performance, an output parameter from a stored procedure.

梦一生花开无言 2024-10-11 03:44:18

我只是在这里猜测,但是:你尝试过这段代码吗?

Nullable<Int32> Result = Command.ExecuteScalar();

if (Result == null) Result = 0;

编辑:现在我已经检查过它,并且它有效:

using (SqlConnection Connection = new SqlConnection())
{
    Connection.ConnectionString = "";
    Connection.Open();

    using (SqlCommand Command = Connection.CreateCommand())
    {
        Command.CommandText = "select 'lol' as [column] where 1 = 0";

        String Result = (String) Command.ExecuteScalar();
    }
}

字符串为空。所以你可以使用 Nullable 就完成了。

I'm only guessing here, but: have you tried with this code?

Nullable<Int32> Result = Command.ExecuteScalar();

if (Result == null) Result = 0;

Edit: Now I've checked it, and it works:

using (SqlConnection Connection = new SqlConnection())
{
    Connection.ConnectionString = "";
    Connection.Open();

    using (SqlCommand Command = Connection.CreateCommand())
    {
        Command.CommandText = "select 'lol' as [column] where 1 = 0";

        String Result = (String) Command.ExecuteScalar();
    }
}

String is null. So you can use Nullable and you're done.

梦醒灬来后我 2024-10-11 03:44:18

这是一篇旧帖子,但万一人们仍在寻找答案,就像我不久前一样:

为什么你不能使用:

IF(ISNUMERIC(@myVariable) = 1)... If你的变量是一个数字。

或者可能是 IF(LEN(@myVariable) > 0)... 对于字符串。

It is an old post but in case people are still looking for the answer like I was not too long ago:

Why could not you use:

IF(ISNUMERIC(@myVariable) = 1)... If your variable is a numeric.

Or maybe IF(LEN(@myVariable) > 0)... for strings.

神经大条 2024-10-11 03:44:18

我使用的是 SQL SERVER 2008 R2。我有同样的任务要完成(当没有实际值可用时返回一些默认值)并且我使用了下面的语句。结果是默认值,但如果我添加“佛罗里达”而不是“英语” - 它将返回“FL”作为州缩写:

--- 声明并给出默认值:
声明 @myVal varchar(10)= '无结果'
select @myVal = StateAbbr FROM dbo.State WHERE StateName = 'English'

--返回值或默认值
选择@myVal

I am using SQL SERVER 2008 R2. I had the same task to accomplish (return some default value when no real value available) and I used statement below. The result is the default value, but if I would add 'Florida' instead of 'English' - it will return 'FL' as state abbreviation:

--- declare and give default value:
declare @myVal varchar(10)= 'No result'
select @myVal = StateAbbr FROM dbo.State WHERE StateName = 'English'

--return value or a default
select @myVal

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文