我有一个从我的数据库填充的数据表。我有一个添加和更新数据的功能,但现在我想检查数据是否存在。但我必须检查两件事
如果数据库中存在数据,请检查它是启用还是禁用,如果启用,则应返回message =“数据存在于表中”,否则“数据已禁用。”
bool nameExists;
connection statement
{
command.Connection = connection;
command.CommandText =
@"SELECT TOP 1 0 " +
@"FROM [dbo].[products] p WITH (NOLOCK) " +
@"WHERE [p].[name] = @name";
command.Parameters.AddWithValue("name", name);
command.CommandTimeout = 100;
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
nameExists = reader.HasRows;
}
connection.Close();
}
如何增强查询以检查上述条件?
注意如果您认为这篇文章不是一篇好文章,请不要降级此帖子而是发表评论。如果我的帖子中存在我的语法错误,也请原谅我。
答案 0 :(得分:2)
如果有一个名为Enabled
的列是int
数据类型,并且0
表示已禁用且1
表示已启用,那么这可能会执行您想要的操作:< / p>
declare @Enabled int;
set @Enabled = (
select top 1
p.Enabled
from dbo.products p with (nolock)
where p.name = @name
);
select
msg = convert(varchar(32), case
when @Enabled is null
then 'Data does not exist'
when @Enabled = 0
then 'Data is disabled'
when @Enabled = 1
then 'Data exist in the table'
end);
答案 1 :(得分:0)
您可以使用SqlCommand.ExecuteScalar Method ()。它总是返回第一行的第一列,如果没有返回行,则返回null
。
using (var connection = new SqlConnection(connectionString))
{
string sql = "SELECT enabled FROM dbo.products WITH(nolock) WHERE name = @name";
using (var command = new SqlCommand(sql, connection)) {
command.Parameters.AddWithValue("name", name);
command.CommandTimeout = 100;
connection.Open();
object enabled = command.ExecuteScalar();
if (enabled == null) {
... // Product does not exist.
} else if ((int)enabled == 0) {
... // Product is disabled.
} else {
... // Product is enabled.
}
}
}
此外,using语句会自动关闭并处理连接和命令。
答案 2 :(得分:0)
您可以更改如下:
bool nameExists;
connection statement
{
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText =
@"SELECT TOP 1 Enabled " +
@"FROM [dbo].[products] p WITH (NOLOCK) " +
@"WHERE [p].[name] = @name";
command.Parameters.AddWithValue("name", name);
command.CommandTimeout = 100;
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
nameExists = reader.HasRows;
if (nameExists)
{
reader.Read();
//bool Enabled = (reader.GetInt32(0) == 1);
bool Enabled = reader.GetBooean(0);
if (Enabled)
return "Data exist in the table";
else
return "Data is disabled.";
}
else
{
throw new Exception ("Data not exist in the table");
}
}
connection.Close();
}